net/http
GoRequest 包含以下功能:
- 支持 HTTP 请求方式:Get/Post/Put/Head/Delete/Patch/Options
- 支持设置 header 请求头
- 支持使用 JSON 字符串作为请求参数
- 支持将多路请求的方式发送数据和文件
- 支持通过代理发送请求
- 支持为请求设置超时
- 支持 TLS 客户端设置
- 支持设置重定向策略
- 支持为请求设置 cookie
- CookieJar - automatic in-memory cookiejar
- 支持请求头设置基本身份认证
安装方式:
go get github.com/parnurzeal/gorequest
02
HTTP 请求方式
net/http
示例代码如下:
标准库方式:
resp, err := http.Get("http://example.com/")
GoRequest 库方式:
request := gorequest.New()
resp, body, errs := request.Get("http://example.com/").End()
或(该 GoRequest 方式无法复用对象)
resp, body, errs := gorequest.New().Get("http://example.com/").End()
阅读上面这两段代码,我们可以发现,使用标准库的方式发送 Get 请求,甚至比使用 GoRequest 库的方式发送 Get 请求更加简单。
但是,当我们需求稍作修改,比如我们需要为 Get 请求,设置 header 头和设置重定向策略。我们再来看一下分别使用标准库和 GoRequest 库两种实现方式。
标准库方式:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
req, err := http.NewRequest("GET", "http://example.com", nil)
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
GoRequest 库方式(其它 HTTP 请求方式与 Get 使用方式相同):
request := gorequest.New()
resp, body, errs := request.Get("http://example.com").
RedirectPolicy(redirectPolicyFunc).
Set("If-None-Match", `W/"wyzzy"`).
End()
阅读上面两段代码,很容易发现使用 GoRequest 方式使实现更加简单。使用标准库方式,首先需要创建一个 Client,然后使用不同的命令设置 header 头等操作,这仅仅是为了实现一个 HTTP 请求。而使用 GoRequest 方式,仅需链式调用两个方法即可轻松实现。
03
JSON 格式请求参数
net/httpencoding/jsonContent-Typeapplication/json
标准库方式:
m := map[string]interface{}{
"name": "backy",
"species": "dog",
}
mJson, _ := json.Marshal(m)
contentReader := bytes.NewReader(mJson)
req, _ := http.NewRequest("POST", "http://example.com", contentReader)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Notes","GoRequest is coming!")
client := &http.Client{}
resp, _ := client.Do(req)
如果使用 GoRequest 库发送请求参数为 JSON 格式的 POST 请求,因为它默认支持 JSON 格式的请求参数,所以它只需要一行代码就可以实现。
GoRequest 库方式:
request := gorequest.New()
resp, body, errs := request.Post("http://example.com").
Set("Notes","gorequst is coming!").
Send(`{"name":"backy", "species":"dog"}`).
End()
04
支持回调函数 Callback
GoRequest 库还支持回调函数,你可以根据自己的项目需求灵活使用它,回调函数示例代码如下:
func printStatus(resp gorequest.Response, body string, errs []error){
fmt.Println(resp.Status)
}
gorequest.New().Get("http://example.com").End(printStatus)
05
请求控制
在 Golang 项目开发中,有时我们可能需要对请求做一些额外控制,比如超时处理,重试请求 N 次,重定向处理等。GoRequest 库都可以为我们提供简单的实现方式。
超时处理:
request := gorequest.New().Timeout(2*time.Millisecond)
resp, body, errs:= request.Get("http://example.com").End()
需要注意的是,Timeout 是将 Dial 连接和 IO 读写的耗时总和,与时间参数作比较。
重试请求:
request := gorequest.New()
resp, body, errs := request.Get("http://example.com/").
Retry(3, 5 * time.Second, http.StatusBadRequest, http.StatusInternalServerError).
End()
http.StatusBadRequesthttp.StatusInternalServerError
重定向处理:
request := gorequest.New()
resp, body, errs := request.Get("http://example.com/").
RedirectPolicy(func(req Request, via []*Request) error {
if req.URL.Scheme != "https" {
return http.ErrUseLastResponse
}
}).
End()
阅读上面这段代码,它的含义是将 http 请求重定向为 https 请求。
06
返回结果处理方式
读者朋友们可能已经发现,以上示例代码都是以 End 结束,End 的含义是返回结果是字符串类型,如果我们希望返回结果是其他类型,比如字节类型和结构体类型,可以将 End 分别替换为 EndBytes 和 EndStruct。
EndBytes 格式:
resp, bodyBytes, errs := gorequest.New().Get("http://example.com/").EndBytes()
EndStruct 格式:
heyYou struct {
Hey string `json:"hey"`
}
var heyYou heyYou
resp, _, errs := gorequest.New().Get("http://example.com/").EndStruct(&heyYou)
07
总结
net/http
http.Clientgorequest.New()
GoRequest 除了上面介绍的 JSON 参数,它还支持 Struct 和 File,感兴趣的读者可以查阅官方文档了解相关内容。
推荐阅读:
参考资料:
https://github.com/parnurzeal/gorequest