[瞎写个 golang 脚本]03- Http 请求

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第10天,点击查看活动详情

前言

本瞎写脚本专题主要是记录使用 golang 一些问题和思考,当然也会将一部分隐私的部分屏蔽掉,只给出一小部分的内容。今天的主要内容是 http请求。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)
复制代码

Http响应

响应由三个部分组成:

  • 响应行:协议、响应状态码和状态描述
  • 响应头部:包含各种头部字段信息,如 cookie
  • 响应体:携带客户端想要的数据

在 Golang 的 net/http 包中,将 http 的响应封装在 http.ResponseWriter结构体

type ResponseWriter interface {
    Header() Header            
    Write([]byte) (int, error) 
    WriteHeader(statusCode int)
}
复制代码
  • Header : 用于设置/ 获取所有响应头信息
  • Writer :用于写入数据到响应实体
  • WriterHeader :用于设置响应状态码

响应返回

请求的响应结果由很多种,我们经常会返回 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 之后,就不能对响应头进行设置了。

猜你喜欢

转载自juejin.im/post/7085361528177688590