Golang http請(qǐng)求封裝的代碼示例
1、POST請(qǐng)求
1.1、POST請(qǐng)求發(fā)送 json
這里發(fā)送json筆者使用了2種方式,一種是golang 自帶的 http.Post方法,另一是 http.NewRequest
方法。二者的區(qū)別是http.Post方法不能發(fā)送自定義的header數(shù)據(jù);而http.NewRequest方法可以發(fā)送額外的自定義header數(shù)據(jù)
先看使用golang 自帶的 http.Post方法封裝的POST請(qǐng)求
func HttpPostJson(url string, requestBody []byte) (string, error) {
response, er := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
if er != nil {
return "", er
}
defer response.Body.Close()
body, er2 := ioutil.ReadAll(response.Body)
if er2 != nil {
return "", er2
}
return string(body), nil
}再看使用http.NewRequest方法封裝的POST請(qǐng)求
看golang的源代碼可以知道 http.Post方法底層就是使用的 NewRequest 方法,因此NewRequest方法更加靈活
func HttpPost(url string, header map[string]string, requestBody []byte) (string, error) {
httpClient := &http.Client{}
request, er := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(requestBody))
if er != nil {
return "", er
}
for key, value := range header {
request.Header.Set(key, value)
}
//設(shè)置請(qǐng)求頭Content-Type
request.Header.Set("Content-Type", "application/json")
response, er2 := httpClient.Do(request)
if er2 != nil {
return "", er2
}
defer response.Body.Close()
body, er3 := ioutil.ReadAll(response.Body)
if er3 != nil {
return "", er3
}
return string(body), nil
}1.2、POST請(qǐng)求發(fā)送form
form數(shù)據(jù)使用map存放,map的key是字符串,value是字符串切片
func HttpPostForm(url string, form map[string][]string) (string, error) {
response, er := http.PostForm(url, form)
if er != nil {
return "", er
}
defer response.Body.Close()
body, er2 := ioutil.ReadAll(response.Body)
if er2 != nil {
return "", er2
}
return string(body), nil
}可以攜帶自定義header的post請(qǐng)求發(fā)送form
筆者使用NewRequest 方法封裝的可以攜帶自定義header的form請(qǐng)求
func HttpPostHeaderForm(requestUrl string, header map[string]string, form map[string][]string) (string, error) {
httpClient := &http.Client{}
var data url.Values
data = map[string][]string{}
for k, v := range form {
data[k] = v
}
request, er := http.NewRequest(http.MethodPost, requestUrl, strings.NewReader(data.Encode()))
if er != nil {
return "", er
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
//設(shè)置自定義header
for key, value := range header {
request.Header.Set(key, value)
}
response, er := httpClient.Do(request)
if er != nil {
return "", er
}
defer response.Body.Close()
body, er2 := ioutil.ReadAll(response.Body)
if er2 != nil {
return "", er2
}
return string(body), nil
}2、GET請(qǐng)求
func HttpGet(url string) (string, error) {
response, er := http.Get(url)
if er != nil {
return "", er
}
defer response.Body.Close()
body, er2 := ioutil.ReadAll(response.Body)
if er2 != nil {
return "", er2
}
return string(body), nil
}3、測(cè)試
這里服務(wù)端筆者使用springboot項(xiàng)目創(chuàng)建,用來接收請(qǐng)求,端口默認(rèn)8080
參數(shù)類
package com.wsjz.demo.param;
import lombok.Data;
@Data
public class AddParam {
private String name;
private Integer age;
}controller
package com.wsjz.demo.controller;
import com.wsjz.demo.param.AddParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
@RestController
public class DemoController {
@PostMapping("/json/add")
public String jsonAdd(@RequestBody AddParam param, HttpServletRequest request) {
System.out.println(request.getHeader("token"));
System.out.println(param);
return "json ok";
}
@PostMapping("/form/add")
public String formAdd(AddParam param, HttpServletRequest request) {
System.out.println(request.getHeader("token"));
System.out.println(param);
return "form ok";
}
@GetMapping("/get/add")
public String getAdd(AddParam param) {
System.out.println(param);
return "get ok";
}
}golang測(cè)試代碼
新建User結(jié)構(gòu)體做為參數(shù)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}(1)、測(cè)試HttpPostJson方法
func TestHttpPostJson(t *testing.T) {
url := "http://localhost:8080/json/add"
var user = User{
Name: "舉頭西北浮云,倚天萬(wàn)里須長(zhǎng)劍,人言此地,夜深長(zhǎng)見,斗牛光焰",
Age: 17,
}
requestBody, er := json.Marshal(user)
if er != nil {
log.Fatal(er)
}
response, er := HttpPostJson(url, requestBody)
if er != nil {
fmt.Println(er)
}
fmt.Println(response)
}運(yùn)行效果

(2)、測(cè)試HttpPost方法
func TestHttpPost(t *testing.T) {
url := "http://localhost:8080/json/add"
var header = make(map[string]string)
header["token"] = "2492dc007dfc4ce8adcc8b42b21641f4"
var user = User{
Name: "我見青山多嫵媚",
Age: 17,
}
requestBody, er := json.Marshal(user)
if er != nil {
log.Fatal(er)
}
response, er2 := HttpPost(url, header, requestBody)
if er2 != nil {
log.Fatal(er2)
}
fmt.Println(response)
}運(yùn)行效果

(3)、測(cè)試HttpPostForm方法
func TestHttpPostForm(t *testing.T) {
url := "http://localhost:8080/form/add"
var form = make(map[string][]string)
form["name"] = []string{"可憐今夕月,向何處,去悠悠"}
form["age"] = []string{"18"}
response, er := HttpPostForm(url, form)
if er != nil {
fmt.Println(er)
}
fmt.Println(response)
}運(yùn)行效果

(4)、測(cè)試HttpPostHeaderForm方法
func TestHttpPostHeaderForm(t *testing.T) {
url := "http://localhost:8080/form/add"
var header = make(map[string]string)
header["token"] = "0a8b903b7d7448e3ab007caab081965c"
var form = make(map[string][]string)
form["name"] = []string{"相思字,空盈幅,相思意,何時(shí)足"}
form["age"] = []string{"18"}
response, er := HttpPostHeaderForm(url, header, form)
if er != nil {
fmt.Println(er)
}
fmt.Println(response)
}運(yùn)行效果

(5)、測(cè)試HttpGet方法
func TestHttpGet(t *testing.T) {
//對(duì)中文進(jìn)行編碼
name := url.QueryEscape("乘風(fēng)好去,長(zhǎng)空萬(wàn)里,直下看山河")
requestUrl := "http://localhost:8080/get/add?name=" + name + "&age=19"
response, er := HttpGet(requestUrl)
if er != nil {
fmt.Println(er)
}
fmt.Println(response)
}運(yùn)行效果

以上就是Golang http請(qǐng)求封裝的代碼示例的詳細(xì)內(nèi)容,更多關(guān)于Golang http請(qǐng)求封裝的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Ubuntu下安裝Go語(yǔ)言開發(fā)環(huán)境及編輯器的相關(guān)配置
這篇文章主要介紹了Ubuntu下安裝Go語(yǔ)言開發(fā)環(huán)境及編輯器的相關(guān)配置,編輯器方面介紹了包括Vim和Eclipse,需要的朋友可以參考下2016-02-02
Golang使用sqlx操作sqlite3數(shù)據(jù)庫(kù)的完整指南
這篇文章主要為大家詳細(xì)介紹了Golang使用sqlx操作sqlite3數(shù)據(jù)庫(kù)的相關(guān)知識(shí),本文會(huì)結(jié)合sqlx給出一些操作數(shù)據(jù)庫(kù)的示例,并將常見功能封裝了函數(shù)接口形式,希望對(duì)大家有所幫助2025-12-12
Go語(yǔ)言協(xié)程池的實(shí)現(xiàn)示例
本文主要介紹了Go語(yǔ)言協(xié)程池的原理與實(shí)現(xiàn),通過限制goroutine數(shù)量避免性能下降,及通過AddTask和Run方法管理任務(wù)分配,確保并發(fā)控制,提升系統(tǒng)穩(wěn)定性,感興趣的可以了解一下2025-09-09

