We can customize the body of the HTTP request we send. Here are some sample code
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func printBody(r *http.Response){
content, err := ioutil.ReadAll(r.Body)
iferr ! =nil {
panic(err)
}
fmt.Printf("%s", content)
}
// Set the request query parameters
func requestByParams(a){
request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get".nil)
iferr ! =nil {
panic(err)
}
params := make(url.Values)
params.Add("name"."yuan")
params.Add("age"."18")
request.URL.RawQuery = params.Encode()
fmt.Println(params.Encode())
resp, err := http.DefaultClient.Do(request)
iferr ! =nil {
panic(err)
}
defer func(a) {_ = resp.Body.Close()}()
printBody(resp)
/ / {
// "args": {
// "age": "18",
// "name": "yuan"
/ /},
// "headers": {
// "Accept-Encoding": "gzip",
// "Host": "httpbin.org",
/ / "the user-agent" : "Go - HTTP client / 1.1",
// "X-Amzn-Trace-Id": "Root=1-60e46b98-58667aee5367f1aa1ca102c9"
/ /},
/ / "origin", "222.211.214.252",
// "url": "http://httpbin.org/get?age=18&name=yuan"
/ /}
}
// Customize the request header
func reauestByHead(a){
request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get".nil)
iferr ! =nil {
panic(err)
}
request.Header.Add("user-agent"."chrome")
resp, err := http.DefaultClient.Do(request)
iferr ! =nil {
panic(err)
}
defer func(a) {_ = resp.Body.Close()}()
printBody(resp)
/ / {
// "args": {},
// "headers": {
// "Accept-Encoding": "gzip",
// "Host": "httpbin.org",
// "User-Agent": "chrome",
// "X-Amzn-Trace-Id": "Root=1-60e46c63-22fd52047229e6175f52166c"
/ /},
/ / "origin", "222.211.214.252",
// "url": "http://httpbin.org/get"
/ /}
}
func main(a) {
requestByParams()
reauestByHead()
}
Copy the code