go原生http请求封装

package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {
    
    

	//get
	// https://test.pet-dbc.cn/api/user/info?name=yuyu
	params :=map[string]string{
    
    
		"name":"yuyu",
	}
	res,err := httpDo("https://test.pet-dbc.cn/api/user/info","GET",
		params,nil,nil)
	if err != nil{
    
    
		fmt.Println(err)
	}
	fmt.Println(res)

	
	//post
	herders :=map[string]string{
    
    
		"Authorization":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyMywiZXhwIjoxODc1MDAwNTI2LCJpc3MiOiJkYmMifQ.Jxw5fwgT2GJDVM3gXLPqv01L2hi7Uf_HjM7F70AopRs",
	}
	type Data struct {
    
    
		UserId int64 `json:"user_id"`
		OrderStatus int64 `json:"order_status"`
		PageSizeNum int64 `json:"page_size_num"`
		Current int64 `json:"current"`
	}
	data := Data{
    
    16,0,10,1}
	body,_ := json.Marshal(data)
	res,err = httpDo("https://test.pet-dbc.cn/api/user/info","POST",
		nil,herders,body)
	if err != nil{
    
    
		fmt.Println(err)
	}
	fmt.Println(res)
}

// @Description 支持任意方式的http请求
// @Param url 请求地址
// @Param method 请求方式
// @Param headers 请求header头设置
// @Param params 请求地址栏后需要拼接参数操作
// @Param data 请求报文
// @Return 返回类型 "错误信息"
func httpDo(url, method string, params,headers map[string]string,data []byte)(interface{
    
    }, error) {
    
    

	//自定义cient
	client := &http.Client{
    
    
		Timeout: 5 * time.Second, // 超时时间:5秒
	}
	//http.post等方法只是在NewRequest上又封装来了一层而已
	req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
	if err != nil {
    
    
		return nil, errors.New("new request is fail: %v \n")
	}
	req.Header.Set("Content-type", "application/json")

	//add params
	q := req.URL.Query()
	if params != nil {
    
    
		for key, val := range params {
    
    
			q.Add(key, val)
		}
		req.URL.RawQuery = q.Encode()
	}

	//add headers
	if headers != nil {
    
    
		for key, val := range headers {
    
    
			req.Header.Add(key, val)
		}
	}

	resp, err := client.Do(req) //  默认的resp ,err :=  http.DefaultClient.Do(req)
	if err != nil {
    
    
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	temp := make(map[string]interface{
    
    }, 0)

	err = json.Unmarshal(body, &temp)

	if err != nil {
    
    
		return nil, err
	}

	return temp,nil
}

猜你喜欢

转载自blog.csdn.net/m0_38004619/article/details/115207105