簡介
net/http
是 Go
語言標準庫的一部分,它提供了創建 HTTP
客戶端和服務器的能力。這個包通過簡化與 HTTP
協議的交互,讓開發者能夠方便地構建 HTTP
請求和響應,以及處理路由等任務。
本文以 net/http
包作為底層,封裝一個包含 get
, post
, form-data
請求的工具包
開始
創建一個項目 demo
,并創建以下目錄:
GET方法
在 client
文件中創建如下方法
package clientimport ("bytes""crypto/tls""fmt""io/ioutil""net/http""net/url""time"
)/***
url 請求地址
header 頭部
requestData 請求數據
*/
func GET(path string,header map[string]string, requestData map[string]string) []byte {if(len(requestData) >0){params := url.Values{}for k,v:=range requestData{params.Add(k,v)}path = path + "?" + params.Encode()}req, _ := http.NewRequest("GET", path, bytes.NewBuffer([]byte("")))req.Header.Set("cache-control", "no-cache")for key,value :=range header{req.Header.Set(key, value)}//過濾https證書tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true},//關閉連接池,不然會打滿語句柄DisableKeepAlives: true,}//設置請求超時時間為20秒client := &http.Client{Transport: tr,Timeout: 20 * time.Second,}res, err := client.Do(req)if res !=nil{defer res.Body.Close()body, _ := ioutil.ReadAll(res.Body)return body}if err !=nil {fmt.Printf("請求錯誤: %s\n", err.Error())return nil}return nil
}
注意:此處需要關閉連接池,不然在多攜程異步調用的時候,由于請求過多,會出現語句餅打滿,導致請求報錯的情況。
POST
/***
url 請求地址
header 頭部
requestData 請求數據,json數據
*/
func POST(path string,header map[string]string, requestData []byte) []byte {req, _ := http.NewRequest("POST", path, bytes.NewBuffer(requestData))req.Header.Set("cache-control", "no-cache")_, ok := header["content-type"]if ok ==false {req.Header.Set("content-type", "application/json")}for key,value :=range header{req.Header.Set(key, value)}//過濾https證書tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true},//關閉連接池,不然會打滿語句柄DisableKeepAlives: true,}//設置請求超時時間為20秒client := &http.Client{Transport: tr,Timeout: 20 * time.Second,}res, err := client.Do(req)if res !=nil{defer res.Body.Close()body, _ := ioutil.ReadAll(res.Body)return body}if err !=nil {fmt.Printf("請求錯誤: %s\n", err.Error())return nil}return nil
}
FormData
/***
url 請求地址
header 頭部
params 其他請求參數
paramName 文件名稱
path 本地文件路徑
*/
func FormData(url string,header map[string]string,params map[string]string, paramName, path string) []byte {file, err := os.Open(path)if err != nil {fmt.Printf("打開文件錯誤: %s\n", err.Error())return nil}defer file.Close()body := &bytes.Buffer{}writer := multipart.NewWriter(body)//fmt.Printf("請求參數:%+v",params)part, err := writer.CreateFormFile(paramName, filepath.Base(path))if err != nil {fmt.Printf("文件錯誤: %s\n", err.Error())return nil}_, err = io.Copy(part, file)for key, val := range params {_ = writer.WriteField(key, val)}err = writer.Close()if err != nil {fmt.Printf("文件關閉錯誤: %s\n", err.Error())return nil}req, err := http.NewRequest("POST", url, body)req.Header.Set("Content-Type", writer.FormDataContentType())for key,value :=range header{req.Header.Set(key, value)}//過濾https證書tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true},//關閉連接池,不然會打滿語句柄DisableKeepAlives: true,}//設置請求超時時間為20秒client := &http.Client{Transport: tr,Timeout: 20 * time.Second,}res, err := client.Do(req)if res !=nil{defer res.Body.Close()body, _ := ioutil.ReadAll(res.Body)return body}if err !=nil {fmt.Printf("請求錯誤: %s\n", err.Error())return nil}return nil
}
Request
/***
url 請求地址
header 頭部
requestData 請求數據
method 請求方法
*/
func Request(url string,header map[string]string, requestData []byte, method string) []byte{//rwLock.Lock()//payload := strings.NewReader(requestData)req, _ := http.NewRequest(method, url, bytes.NewBuffer(requestData))//req.Header.Set("content-type", "application/json")req.Header.Set("cache-control", "no-cache")for key,value :=range header{req.Header.Set(key, value)}//過濾https證書tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true},//關閉連接池,不然會打滿語句柄DisableKeepAlives: true,}//設置請求超時時間為20秒client := &http.Client{Transport: tr,Timeout: 20 * time.Second,}res, err := client.Do(req)if res !=nil{defer res.Body.Close()body, _ := ioutil.ReadAll(res.Body)return body}if err !=nil {fmt.Printf("請求錯誤: %s\n", err.Error())return nil}return nil}
測試
新建 main.go
文件寫入以下內容:
func main() {sendData :=make(map[string]string)sendData["name"]="測試"sendData["sex"]="男"jsonStr,_:=json.Marshal(sendData)//此處需要換成你自己的接口地址httpUrl:="https://xxxxx/api/test"headerData :=make(map[string]string)headerData["X-Ca-Key"]="22527885"headerData["Content-Type"]="application/json;charset=UTF-8"headerData["Accept"]="application/json"body:=client.POST(httpUrl,headerData,jsonStr)fmt.Printf("請求成功返回:%s\n",body)}
執行命令:
go run main.go
總結
本文對 net/http
包的簡單封裝,使用者可以直接拿來用,減少了開發成本。