下面展示一些 内联代码片
。
import (
"bytes"
"encoding/json"
"io"
"net/http"
)
type postTP struct { //请求Body示例()
name string
age int
}
func main() {
url := "localhost:8080"//请求地址
//请求体实例化
posTP := postTP{
name: "admin",
age: 0,
}
marshal, _ := json.Marshal(posTP)
postbody := bytes.NewBuffer(marshal)
request, _ := http.NewRequest(http.MethodPost, url, postbody)//http.MethodPost为方法,常用还有GET PUT
//设置参数绑定到URL
qry := request.URL.Query()
qry.Add("key", "value")
request.URL.RawQuery = qry.Encode()
//
//设置轻轻头
request.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(request)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
}