golang人性化HTTP请求处理插件库request的使用
Golang 人性化 HTTP 请求处理插件库 request 的使用
request 是一个为 Gopher 设计的开发者友好的 HTTP 请求库,灵感来源于 Python-Requests。
安装
go get -u github.com/mozillazg/request
使用示例
基本导入
import (
"github.com/mozillazg/request"
)
GET 请求
c := new(http.Client)
req := request.NewRequest(c)
resp, err := req.Get("http://httpbin.org/get")
j, err := resp.Json()
defer resp.Body.Close() // 不要忘记关闭响应体
POST 请求
req := request.NewRequest(c)
req.Data = map[string]string{
"key": "value",
"a": "123",
}
resp, err := req.Post("http://httpbin.org/post")
Cookies
req := request.NewRequest(c)
req.Cookies = map[string]string{
"key": "value",
"a": "123",
}
resp, err := req.Get("http://httpbin.org/cookies")
Headers
req := request.NewRequest(c)
req.Headers = map[string]string{
"Accept-Encoding": "gzip,deflate,sdch",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
}
resp, err := req.Get("http://httpbin.org/get")
文件上传
req := request.NewRequest(c)
f, err := os.Open("test.txt")
req.Files = []request.FileField{
request.FileField{"file", "test.txt", f},
}
resp, err := req.Post("http://httpbin.org/post")
JSON 数据
req := request.NewRequest(c)
req.Json = map[string]string{
"a": "A",
"b": "B",
}
resp, err := req.Post("http://httpbin.org/post")
req.Json = []int{1, 2, 3}
resp, err = req.Post("http://httpbin.org/post")
代理
req := request.NewRequest(c)
req.Proxy = "http://127.0.0.1:8080"
// req.Proxy = "https://127.0.0.1:8080"
// req.Proxy = "socks5://127.0.0.1:57341"
resp, err := req.Get("http://httpbin.org/get")
HTTP 基本认证
req := request.NewRequest(c)
req.BasicAuth = request.BasicAuth{"user", "passwd"}
resp, err := req.Get("http://httpbin.org/basic-auth/user/passwd")
完整示例
下面是一个完整的示例,展示了如何使用 request 库发送 GET 和 POST 请求:
package main
import (
"fmt"
"net/http"
"github.com/mozillazg/request"
)
func main() {
// 创建 HTTP 客户端
c := new(http.Client)
// 示例1: GET 请求
req := request.NewRequest(c)
resp, err := req.Get("http://httpbin.org/get")
if err != nil {
fmt.Println("GET 请求出错:", err)
return
}
j, err := resp.Json()
if err != nil {
fmt.Println("解析 JSON 出错:", err)
return
}
fmt.Println("GET 响应:", j)
resp.Body.Close()
// 示例2: POST 请求
req = request.NewRequest(c)
req.Data = map[string]string{
"name": "John",
"age": "30",
}
resp, err = req.Post("http://httpbin.org/post")
if err != nil {
fmt.Println("POST 请求出错:", err)
return
}
j, err = resp.Json()
if err != nil {
fmt.Println("解析 JSON 出错:", err)
return
}
fmt.Println("POST 响应:", j)
resp.Body.Close()
}
许可证
MIT 许可证。
更多关于golang人性化HTTP请求处理插件库request的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang人性化HTTP请求处理插件库request的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang人性化HTTP请求处理库 - Request
Request是一个简单易用的Go语言HTTP客户端库,它提供了更加人性化的API来发送HTTP请求。下面我将详细介绍它的使用方法和示例代码。
安装
go get github.com/parnurzeal/gorequest
基本用法
1. 简单GET请求
package main
import (
"fmt"
"github.com/parnurzeal/gorequest"
)
func main() {
_, body, errs := gorequest.New().Get("https://httpbin.org/get").End()
if errs != nil {
fmt.Println("请求出错:", errs)
return
}
fmt.Println("响应内容:", body)
}
2. 带参数的GET请求
func main() {
request := gorequest.New()
_, body, errs := request.Get("https://httpbin.org/get").
Query("name=John").
Query("age=30").
End()
// 或者使用map添加参数
params := map[string]string{
"city": "New York",
"job": "developer",
}
_, body, errs = request.Get("https://httpbin.org/get").
Query(params).
End()
}
3. POST请求发送JSON数据
func main() {
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
user := User{
Name: "Alice",
Age: 25,
}
_, body, errs := gorequest.New().
Post("https://httpbin.org/post").
Send(user).
End()
if errs != nil {
fmt.Println("请求出错:", errs)
return
}
fmt.Println("响应内容:", body)
}
4. 设置请求头
func main() {
_, body, errs := gorequest.New().
Get("https://httpbin.org/headers").
Set("Authorization", "Bearer token123").
Set("X-Custom-Header", "value").
End()
}
5. 处理响应
func main() {
type Response struct {
Args map[string]string `json:"args"`
Headers map[string]string `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
}
var resp Response
res, body, errs := gorequest.New().
Get("https://httpbin.org/get").
Query("param1=value1").
EndStruct(&resp) // 直接将响应解析到结构体
if errs != nil {
fmt.Println("请求出错:", errs)
return
}
fmt.Println("状态码:", res.StatusCode)
fmt.Println("解析后的响应:", resp)
fmt.Println("原始响应体:", body)
}
6. 超时设置
func main() {
_, _, errs := gorequest.New().
Get("https://httpbin.org/delay/5"). // 这个端点会延迟5秒响应
Timeout(2 * time.Second). // 设置2秒超时
End()
if errs != nil {
fmt.Println("请求超时:", errs) // 会返回超时错误
}
}
7. 文件上传
func main() {
_, body, errs := gorequest.New().
Post("https://httpbin.org/post").
Type("multipart").
SendFile("./test.txt").
End()
}
8. 重试机制
func main() {
_, body, errs := gorequest.New().
Get("https://unstable-api.example.com").
Retry(3, 5 * time.Second, http.StatusBadRequest, http.StatusInternalServerError).
End()
}
高级特性
1. 中间件支持
func main() {
request := gorequest.New()
// 添加前置中间件
request = request.AppendMiddleware(func(r *gorequest.SuperAgent, next gorequest.Handler) gorequest.Handler {
return func(r2 *gorequest.SuperAgent, h gorequest.Handler) (gorequest.Response, string, []error) {
fmt.Println("请求前:", r2.Url)
return next(r2, h)
}
})
// 添加后置中间件
request = request.AppendMiddleware(func(r *gorequest.SuperAgent, next gorequest.Handler) gorequest.Handler {
return func(r2 *gorequest.SuperAgent, h gorequest.Handler) (gorequest.Response, string, []error) {
res, body, errs := next(r2, h)
fmt.Println("请求后, 状态码:", res.StatusCode)
return res, body, errs
}
})
request.Get("https://httpbin.org/get").End()
}
2. 代理设置
func main() {
_, body, _ := gorequest.New().
Proxy("http://proxy.example.com:8080").
Get("https://httpbin.org/get").
End()
}
3. 自定义HTTP客户端
func main() {
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: 10 * time.Second,
}
_, body, _ := gorequest.New().
CustomClient(client).
Get("https://httpbin.org/get").
End()
}
错误处理
Request库返回的错误是一个[]error
切片,因为可能有多个错误发生:
func main() {
_, _, errs := gorequest.New().
Get("https://nonexistent.example.com").
End()
if errs != nil {
for _, err := range errs {
fmt.Println("错误:", err)
}
}
}
总结
Request库相比标准库net/http
提供了更加简洁易用的API,主要优点包括:
- 链式调用,代码更简洁
- 内置JSON处理
- 支持文件上传
- 提供重试机制
- 支持中间件
- 更友好的错误处理
对于简单的HTTP请求场景,Request库可以大大减少样板代码,提高开发效率。但对于需要高度定制化的HTTP客户端场景,可能还是需要使用标准库。
希望这些示例能帮助你快速上手Request库的使用!