本瞎写脚本专题主要是记录使用 golang 一些问题和思考,当然也会将一部分隐私的部分屏蔽掉,只给出一小部分的内容。今天的主要内容是 http请求。Http 请求都是由请求和响应构成的。
Golang 中提供了 net/http库 ,可以直接通过此库进行 http 请求 GET,POST 等。
// 不带参数的 get 请求
resp, err := http.Get("https://www.test.yuanyuzhou.com/")
// 带参数的 get 请求,可以使用 newRequest
resp, err := http.NewRequest(http.MethodGet, url, nil)
params := resp.URL.Query()
params.add(key,value)
// Post 请求
resp, err := http.Post("https://www.test.yuanyuzhou.com","application/json",string.NewReader("key=value"))
// 如果需要设置头参数
resp.Header.Set("Cookie","saushajshauydia")
// Form 提交表单
params := url.Values{key:value}
http.PostForm("http://" ,params)
复制代码
响应由三个部分组成:
在 Golang 的 net/http 包中,将 http 的响应封装在 http.ResponseWriter结构体
type ResponseWriter interface {
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
}
复制代码
请求的响应结果由很多种,我们经常会返回 json 格式,文本信息,或者进行重定向。
返回文本
func responseBack(w http.ResponseWriter, r *http.Request){
w.Write([]byte("我是返回文本结果"))
}
复制代码
返回 JSON 格式数据
type ResJson struct {
Code string `json:code`
Message string `json:message`
}
resJson := ResJson{
200,
"返回 Json 格式数据"
}
w.Header().Set("Content-Type", "application/json")
w.Write(json.Marshal(resJson))
复制代码
返回 Json 格式数据时,需要设置 header 的 contentType 内容为 application/ json
,这样返回结果才是 json 格式
重定向
func Redirect(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", "https://xueyuanjun.com")
w.WriteHeader(301)
}
复制代码
需要注意,重定向请求,不需要设置响应实体,另外需要注意的是 w.Header().Set
必须在 w.WriteHeader
之前调用,因为一旦调用 w.WriteHeader
之后,就不能对响应头进行设置了。
参考:GO Gin框架的Post/Get请求示例_dreamer'~的博客-CSDN博客_gin post请求
链接:https://juejin.cn/post/7085361528177688590