golang之http请求库go-resty
github: https://github.com/go-resty/resty
go-resty 特性#
go-resty 有很多特性:
- 发起 GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc. 请求
- 简单的链式书写
- 自动解析 JSON 和 XML 类型的文档
- 上传文件
- 重试功能
- 客户端测试功能
- Resty client
- Custom Root Certificates and Client Certificates
- ... ....
等等很多特性。
go-resty更多功能特性请查看文档:go-resty features
go-resty 使用#
go-resty: v2.3.0
用法 example:https://github.com/go-resty/resty#usage
[GET]
package main import (
"fmt" "github.com/go-resty/resty/v2"
) func main() {
client := resty.New() // 创建一个restry客户端
resp, err := client.R().EnableTrace().Get("https://httpbin.org/get") // Explore response object
fmt.Println("Response Info:")
fmt.Println(" Error :", err)
fmt.Println(" Status Code:", resp.StatusCode())
fmt.Println(" Status :", resp.Status())
fmt.Println(" Proto :", resp.Proto())
fmt.Println(" Time :", resp.Time())
fmt.Println(" Received At:", resp.ReceivedAt())
fmt.Println(" Body :\n", resp)
fmt.Println() // Explore trace info
fmt.Println("Request Trace Info:")
ti := resp.Request.TraceInfo()
fmt.Println(" DNSLookup :", ti.DNSLookup)
fmt.Println(" ConnTime :", ti.ConnTime)
fmt.Println(" TCPConnTime :", ti.TCPConnTime)
fmt.Println(" TLSHandshake :", ti.TLSHandshake)
fmt.Println(" ServerTime :", ti.ServerTime)
fmt.Println(" ResponseTime :", ti.ResponseTime)
fmt.Println(" TotalTime :", ti.TotalTime)
fmt.Println(" IsConnReused :", ti.IsConnReused)
fmt.Println(" IsConnWasIdle :", ti.IsConnWasIdle)
fmt.Println(" ConnIdleTime :", ti.ConnIdleTime)
// fmt.Println(" RequestAttempt:", ti.RequestAttempt)
// fmt.Println(" RemoteAddr :", ti.RemoteAddr.String())
}client := resty.New()
resp, err := client.R().
SetQueryParams(map[string]string{
"page_no": "1",
"limit": "20",
"sort": "name",
"order": "asc",
"random": strconv.FormatInt(time.Now().Unix(), 10),
}).
SetHeader("Accept", "application/json").
SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
Get("/search_result") // Request.SetQueryString method
resp, err := client.R().
SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
SetHeader("Accept", "application/json").
SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
Get("/show_product") // 解析返回的内容,内容是json解析到struct
resp, err := client.R().
SetResult(result).
ForceContentType("application/json").
Get("v2/alpine/mainfestes/latest")
[POST]
// Create a Resty Clientclient := resty.New() // POST JSON string// No need to set content type, if you have client level settingresp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(`{"username":"testuser", "password":"testpass"}`).
SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
Post("https://myapp.com/login") // POST []byte array// No need to set content type, if you have client level settingresp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
Post("https://myapp.com/login") // POST Struct, default is JSON content type. No need to set oneresp, err := client.R().
SetBody(User{Username: "testuser", Password: "testpass"}).
SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
SetError(&AuthError{}). // or SetError(AuthError{}).
Post("https://myapp.com/login") // POST Map, default is JSON content type. No need to set oneresp, err := client.R().
SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
SetError(&AuthError{}). // or SetError(AuthError{}).
Post("https://myapp.com/login") // POST of raw bytes for file upload. For example: upload file to DropboxfileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf") // See we are not setting content-type header, since go-resty automatically detects Content-Type for youresp, err := client.R().
SetBody(fileBytes).
SetContentLength(true). // Dropbox expects this value
SetAuthToken("<your-auth-token>").
SetError(&DropboxError{}). // or SetError(DropboxError{}).
Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // for upload Dropbox supports PUT too // Note: resty detects Content-Type for request body/payload if content type header is not set.// * For struct and map data type defaults to 'application/json'// * Fallback is plain text content type[PUT]
// Note: This is one sample of PUT method usage, refer POST for more combination // Create a Resty Clientclient := resty.New() // Request goes as JSON content type// No need to set auth token, error, if you have client level settingsresp, err := client.R().
SetBody(Article{
Title: "go-resty",
Content: "This is my article content, oh ya!",
Author: "Jeevanandam M",
Tags: []string{"article", "sample", "resty"},
}).
SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
SetError(&Error{}). // or SetError(Error{}).
Put("https://myapp.com/article/1234")[PATCH]
// Note: This is one sample of PUT method usage, refer POST for more combination // Create a Resty Clientclient := resty.New() // Request goes as JSON content type// No need to set auth token, error, if you have client level settingsresp, err := client.R().
SetBody(Article{
Tags: []string{"new tag1", "new tag2"},
}).
SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
SetError(&Error{}). // or SetError(Error{}).
Patch("https://myapp.com/articles/1234")
[DELETE,HEAD,OPTIONS]
// Create a Resty Clientclient := resty.New() // DELETE a article// No need to set auth token, error, if you have client level settingsresp, err := client.R().
SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
SetError(&Error{}). // or SetError(Error{}).
Delete("https://myapp.com/articles/1234") // DELETE a articles with payload/body as a JSON string// No need to set auth token, error, if you have client level settingsresp, err := client.R().
SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
SetError(&Error{}). // or SetError(Error{}).
SetHeader("Content-Type", "application/json").
SetBody(`{article_ids: [1002, 1006, 1007, 87683, 45432] }`).
Delete("https://myapp.com/articles") // HEAD of resource// No need to set auth token, if you have client level settingsresp, err := client.R().
SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
Head("https://myapp.com/videos/hi-res-video") // OPTIONS of resource// No need to set auth token, if you have client level settingsresp, err := client.R().
SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
Options("https://myapp.com/servers/nyc-dc-01")[REQUEST & RESPONSE 中间件]
// Create a Resty Clientclient := resty.New() // Registering Request Middlewareclient.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
// Now you have access to Client and current Request object
// manipulate it as per your need return nil // if its success otherwise return error
}) // Registering Response Middlewareclient.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
// Now you have access to Client and current Response object
// manipulate it as per your need return nil // if its success otherwise return error
})
[重试]
// Create a Resty Clientclient := resty.New() // Retries are configured per clientclient.
// Set retry count to non zero to enable retries
SetRetryCount(3).
// You can override initial retry wait time.
// Default is 100 milliseconds.
SetRetryWaitTime(5 * time.Second).
// MaxWaitTime can be overridden as well.
// Default is 2 seconds.
SetRetryMaxWaitTime(20 * time.Second).
// SetRetryAfter sets callback to calculate wait time between retries.
// Default (nil) implies exponential backoff with jitter
SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) {
return 0, errors.New("quota exceeded")
})Above setup will result in resty retrying requests returned non nil error up to 3 times with delay increased after each attempt.
You can optionally provide client with custom retry conditions:
// Create a Resty Clientclient := resty.New() client.AddRetryCondition(
// RetryConditionFunc type is for retry condition function
// input: non-nil Response OR request execution error
func(r *resty.Response) (bool, error) {
return r.StatusCode() == http.StatusTooManyRequests
},
)[多客户端请求]
// Here you go!// Client 1client1 := resty.New()
client1.R().Get("http://httpbin.org")
// ... // Client 2client2 := resty.New()
client2.R().Head("http://httpbin.org")
// ... // Bend it as per your need!!!更多参考:
golang之http请求库go-resty的更多相关文章
- 浅论Android网络请求库——android-async-http
在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Insta ...
- swift中第三方网络请求库Alamofire的安装与使用
swift中第三方网络请求库Alamofire的安装与使用 Alamofire是swift中一个比较流行的网络请求库:https://github.com/Alamofire/Alamofire.下面 ...
- [转]Android各大网络请求库的比较及实战
自己学习android也有一段时间了,在实际开发中,频繁的接触网络请求,而网络请求的方式很多,最常见的那么几个也就那么几个.本篇文章对常见的网络请求库进行一个总结. HttpUrlConnection ...
- Android之网络请求库
自己学习android也有一段时间了,在实际开发中,频繁的接触网络请求,而网络请求的方式很多,最常见的那么几个也就那么几个.本篇文章对常见的网络请求库进行一个总结. HttpUrlConnection ...
- 自己动手写一个iOS 网络请求库的三部曲[转]
代码示例:https://github.com/johnlui/Swift-On-iOS/blob/master/BuildYourHTTPRequestLibrary 开源项目:Pitaya,适合大 ...
- 【转载】一步一步搭建自己的iOS网络请求库
一步一步搭建自己的iOS网络请求库(一) 大家好,我是LastDay,很久没有写博客了,这周会分享一个的HTTP请求库的编写经验. 简单的介绍 介绍一下,NSURLSession是iOS7中新的网络接 ...
- Android进阶笔记02:Android 网络请求库的比较及实战(二)
一.Volley 既然在android2.2之后不建议使用HttpClient,那么有没有一个库是android2.2及以下版本使用HttpClient,而android2.3及以上版本 ...
- Android进阶笔记01:Android 网络请求库的比较及实战(一)
在实际开发中,有的时候需要频繁的网络请求,而网络请求的方式很多,最常见的也就那么几个.本篇文章对常见的网络请求库进行一个总结. 一.使用HttpUrlConnection: 1. HttpUrlCon ...
- Retrofit网络请求库应用01
PS:什么是Retrofit? 在官方文档中有这样一句话--A type-safe HTTP client for Android and Java(一个类型安全的http client库),具体的话 ...
- Retrofit网络请求库应用02——json解析
PS:上一篇写了Retrofit网络请求库的简单使用,仅仅是获取百度的源码,来证明连接成功,这篇讲解如何解析JSON数据,该框架不再是我们之前自己写的那样用JsonArray等来解析,这些东西,我们都 ...
随机推荐
- P9032 [COCI2022-2023#1] Neboderi
题意 给长度为 \(n\) 的数组 \(a\),求长度不小于 \(k\) 的区间 \([l,r]\) 使得 \(\gcd_{i = l}^r a_i \times \sum_{i = l}^r a_i ...
- EF Core – JSON Column
前言 SQL Server 支持 JSON, 以前写过一篇介绍 SQL Server – Work with JSON. 但 EF Core 一直没有支持. 直到 EF Core 7.0 才支持. 参 ...
- Flutter Engage China 开发者常见问题解答 | 下篇
再次感谢大家对 Flutter Engage China 活动 的关注和积极参与!我们在活动前后收到了很多来自开发者的反馈和问题,Flutter 团队和演讲嘉宾在直播 Q&A 环节中也针对部分 ...
- 北京智和信通受邀出席2022IT运维大会,荣获“2022智能运维星耀榜最具影响力企业”
9月8日,由IT运维网.<网络安全和信息化>杂志社联合主办的"2022(第十三届)IT运维大会"在北京辽宁大厦成功举办.大会以"智慧先行,运维有术" ...
- LeetCode 1388. Pizza With 3n Slices(3n 块披萨)(DP)
给你一个披萨,它由 3n 块不同大小的部分组成,现在你和你的朋友们需要按照如下规则来分披萨: 你挑选 任意 一块披萨.Alice 将会挑选你所选择的披萨逆时针方向的下一块披萨.Bob 将会挑选你所选择 ...
- `operator++(int)` 和 `operator++()`
operator++(int) 和 operator++() 是 C++ 中重载的两个不同的自增运算符函数,它们分别用于后置自增和前置自增.它们的区别在于调用方式以及自增行为的不同. 1. 前置自增运 ...
- Access to XMLHttpRequest at xxxx from origin xxx has been blocked by CORS policy: No 'Access-Control- Allow-Origin' header is present on the requested resource
错误:控制台报错 : network 自动发起了请求: 解决办法: 找到 \node_modules\sockjs-client\dist\sockjs.js 文件 然后 crtl + g 快捷键跳 ...
- python中的时间处理
python程序编写中的时间处理涉及三种: 1.时间的显示: 2.时间的转换: 3.时间的运算. 时间处理模块:time模块 时间的三种表示方式: ①时间戳,从1970年1月1日开始,每过1s增加1, ...
- CentOS 7.6 内网穿透服务lanproxy部署
在很多场景下内网穿透都是我们常常遇到的需求,之前也用过花生壳.ngrok.FRP 等等一些工具,但是由于限速.收费.安全各方面因素只好放弃了. 近期无意间看到 「传送门:lanproxy」 这款开源工 ...
- Taylor series Explicit Euler Implicit Euler
1 Taylor series \[\begin{gathered}\sum_{n=0}^{\infty}\frac{f^{(n)}\left(a\right)}{n!}\left(x-a\right ...