• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Go语言中最便捷的http请求包resty的使用详解

    发布者: 皮3591 | 发布时间: 2025-8-14 10:20| 查看数: 45| 评论数: 0|帖子模式

    go语言虽然自身就有net/http包,但是说实话用起来没那么好用。resty包是go语言中一个非常受欢迎的http请求处理包,它的api非常简洁、属于一看就懂的那种、对新手非常有友好。它支持链式调用、支持超时、重试机制,还支持中间件,可以在请求发送前,发送后做些操作,使用起来非常舒服。 今天我们一起来看下吧。

    安装

    先来安装下
    1. go get github.com/go-resty/resty/v2
    复制代码

    一、一个简单的get

    发一个get请求试试呢?
    1. package main

    2. import (
    3.         "fmt"

    4.         "github.com/go-resty/resty/v2"
    5. )

    6. func main() {
    7.         client := resty.New()

    8.         resp, err := client.R().
    9.                 Get("https://www.baidu.com")

    10.         if err != nil {
    11.                 fmt.Println("请求出错:", err)
    12.                 return
    13.         }

    14.         fmt.Println("状态码:", resp.StatusCode())
    15.         fmt.Println("响应体:", resp.String())
    16.         fmt.Println("响应头:", resp.Header())                       // 获取全部header
    17.         fmt.Println("特定响应头:", resp.Header().Get("Content-Type")) // 获取特定的header
    18.         // 状态码: 200
    19.         // 响应体: xxx太多了省略掉...
    20.         // 响应头: map[Accept-Ranges:[bytes] Cache-Control:[no-cache] Connection:[keep-alive] Content-Length:[227] Content-Security-Policy:[frame-ancestors 'self' https://chat.baidu.com http://mirror-chat.baidu.com https://fj-chat.baidu.com https://hba-chat.baidu.com https://hbe-chat.baidu.com https://njjs-chat.baidu.com https://nj-chat.baidu.com https://hna-chat.baidu.com https://hnb-chat.baidu.com http://debug.baidu-int.com;] Content-Type:[text/html] Date:[Sun, 16 Mar 2025 09:43:18 GMT] P3p:[CP=" OTI DSP COR IVA OUR IND COM " CP=" OTI DSP COR IVA OUR IND COM "] Pragma:[no-cache] Server:[BWS/1.1] Set-Cookie:[BD_NOT_HTTPS=1; path=/; Max-Age=300 BIDUPSID=10846246655E82CCF356A792677D7EA8; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com PSTM=1742118198; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com BAIDUID=10846246655E82CC89D4B0052594BBBE:FG=1; max-age=31536000; expires=Mon, 16-Mar-26 09:43:18 GMT; domain=.baidu.com; path=/; version=1; comment=bd] Traceid:[1742118198045022490612843349543995319034] X-Ua-Compatible:[IE=Edge,chrome=1] X-Xss-Protection:[1;mode=block]]
    21.         // 特定响应头: text/html
    22. }
    复制代码
    使用起来非常简单,它支持链式调用,唯一需要注意的是**
    1. 请求方式 + 路径
    复制代码
    要放在最后——它返回响应**。

    二、带查询参数
    1. resp, err := client.R().
    2.         SetQueryParam("postId", "1"). // 设置单个查询参数 也是可以的
    3.         Get("https://jsonplaceholder.typicode.com/posts")

    4. // resp, err := client.R().
    5. //         SetQueryParams(map[string]string{ // 设置多个查询参数
    6. //                 "postId": "1",
    7. //         }).
    8. //         Get("https://jsonplaceholder.typicode.com/posts")
    复制代码
    它支持一次设置多个查询参数
    1. SetQueryParams
    复制代码
    、和单个查询参数
    1. SetQueryParam
    复制代码
    两种方式方式。

    三、设置请求头、body

    由于支持链式调用,设置请求头也很方便
    1.         resp, err := client.R().
    2.                 SetHeader("Content-Type", "application/json"). // 设置单个请求头
    3.                 SetBody(`{"title": "foo", "body": "bar", "userId": 1}`). // 字符串形式
    4.                 Post("https://jsonplaceholder.typicode.com/posts")

    5.         resp, err := client.R().
    6.                 SetBody(map[string]interface{}{ // 支持 map结构
    7.                         "title":  "foo",
    8.                         "body":   "bar",
    9.                         "userId": 1,
    10.                 }).
    11.                 SetHeaders(map[string]string{  // 设置多个请求头
    12.                         "Content-Type": "application/json",
    13.                 }).
    14.                 Post("https://jsonplaceholder.typicode.com/posts")

    15.         resp, err := client.R().
    16.                 SetBody(Post{Title: "foo", Body: "bar", UserId: 1}). // 支持struct
    17.                 SetHeaders(map[string]string{
    18.                         "Content-Type": "application/json",
    19.                 }).
    20.                 Post("https://jsonplaceholder.typicode.com/posts")

    21.         // 从文件创建 io.Reader
    22.         file, err := os.Open("my_file.txt")
    23.         if err != nil {
    24.                         // ... 错误处理 ...
    25.         }
    26.         defer file.Close()
    27.         resp, err := client.R().
    28.                         // 不设置也可以, resty会根据reader自动推断content-type
    29.                         SetHeader("Content-Type", "application/octet-stream"). // 或者根据文件类型设置
    30.                         SetBody(file). // 支持 io.Reader方式
    31.                         Post("https://example.com/upload")
    复制代码

      1. SetBody
      复制代码
      支持方式非常丰富
      1. json字符串
      复制代码
      1. map
      复制代码
      1. struct
      复制代码
      1. []byte
      复制代码
      1. io.Reader
      复制代码
    • 设置请求头和前面的设置查询参数类似,同时支持单个、多个
      1. 复数s
      复制代码
      两种方式。

    四、设置表单数据
    1. resp, err := client.R().
    2.                 SetFormData(map[string]string{"title": "foo", "body": "bar", "userId": "1"}).
    3.                 Post("https://jsonplaceholder.typicode.com/posts")
    复制代码
    需要注意
    1. SetFormData
    复制代码
    参数只支持
    1. map[string]string
    复制代码
    类型。

    五、处理响应
    1. // 请求
    2.         type postReq struct {
    3.                 Title  string `json:"title"`
    4.                 Body   string `json:"body"`
    5.                 UserId int    `json:"userId"`
    6.         }

    7.         // 响应
    8.         type postRes struct {
    9.                 ID     int    `json:"id"`
    10.                 Title  string `json:"title"`
    11.                 Body   string `json:"body"`
    12.                 UserId int    `json:"userId"`
    13.         }

    14.         var pr postRes

    15.         resp, err := client.R().
    16.                 SetHeader("Content-Type", "application/json").
    17.                 SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
    18.                 SetResult(&pr). // 设置响应后内容
    19.                 Post("https://jsonplaceholder.typicode.com/posts")

    20.         if err != nil {
    21.                 fmt.Println("请求出错:", err)
    22.                 return
    23.         }

    24.         fmt.Println("请求成功了么?", resp.IsSuccess()) // 是否响应成了
    25.         fmt.Printf("响应结果:%#v\n", pr)
    26.         // 请求成功了么? true
    27.         // 响应结果:main.postRes{ID:101, Title:"foo", Body:"bar", UserId:1}
    复制代码

      1. IsSuccess
      复制代码
      判断 响应是否成
      1. SetResult
      复制代码
      支持把响应结果映射到结构体中

    六、超时与重试
    1.         client := resty.New().
    2.                 SetTimeout(5 * time.Second).          // 设置超时时间
    3.                 SetRetryCount(3).                     // 设置重试次数为 3
    4.                 SetRetryWaitTime(1 * time.Second).    // 设置重试间隔为 1 秒
    5.                 SetRetryMaxWaitTime(5 * time.Second). //最大重试间隔
    6.                 AddRetryCondition(
    7.                         func(r *resty.Response, err error) bool {
    8.                                 return r.StatusCode() == http.StatusTooManyRequests // 429 错误时重试
    9.                         },
    10.                 )

    11.         resp, err := client.R().
    12.                 SetHeader("Content-Type", "application/json").
    13.                 SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
    14.                 SetResult(&pr).
    15.                 Post("https://jsonplaceholder.typicode.com/posts")
    复制代码
    需要之一的是
    1. resty.New()
    复制代码
    和 下面的
    1. client.R()
    复制代码
    是不同的类,前者主要用于设置全局性相关的设置(比如:超时、重试等); 后者主要用于请求的发送相关设置;

    七、调试模式
    1. resp, err := client.R().
    2.                 SetHeader("Content-Type", "application/json").
    3.                 SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
    4.                 SetResult(&pr).
    5.                 SetDebug(true). // 开启调试模式
    6.                 Post("https://jsonplaceholder.typicode.com/posts")
    复制代码
    调试模式开启,请求的所有参数、和响应内容都可以看到。

    八、中间件
    1. client := resty.New()

    2. // 请求中间件
    3. client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
    4.         fmt.Println("发送请求前:", req.URL)
    5.         // 可以修改请求, 比如 req.SetHeader("New-Header", "value")
    6.         return nil
    7. })

    8. // 响应中间件
    9. client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
    10.         fmt.Println("收到响应后:", resp.Status())
    11.         return nil
    12. })

    13. resp, err := client.R().
    14.         SetHeader("Content-Type", "application/json").
    15.         SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
    16.         SetResult(&pr).
    17.         Post("https://jsonplaceholder.typicode.com/posts")
    复制代码
    它也支持中间件,在发送请求前、请求后做些处理。
    到此这篇关于Go语言中最便捷的http请求包resty的使用详解的文章就介绍到这了,更多相关Go resty使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:互联网
    免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作!

    最新评论

    浏览过的版块

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表