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等来解析,这些东西,我们都 ...
随机推荐
- MVCC能否解决幻读?
一.什么是MVCC 多版本控制: 指的是一种提高并发的技术.最早的数据库系统,只有读读之间可以并发,读写,写读,写写都要阻塞.引入多版本之后,只有写写之间相互阻塞,其他三种操作都可以并行,这样大幅度提 ...
- ComfyUI 基础教程(三) —— 应用 Controlnet 精准控制图像生成
一.前言 你是否有见过下面类似这样的图片: 看起来平平无奇,当你站远点看,或者把眼睛眯成一条缝了看,你会发现,这个图中藏有一些特别的元素.这就是利用了 Ai 绘画中的 ControlNet,实现对图片 ...
- BOM – Cookie 和 LocalStorage
前言 Cookie 和 LocalStorage 是非常基础的东西. 我是学编程后, 第 3 年才开始写博客的, 所以很多在第 1, 2 年学的知识完全都没有记入下来. (比如 C#, JS 语法等等 ...
- CSS & JS Effect – Hero Banner Swiper
效果 重点 1. 一张图片, 一个 content 定位居中作为一个 slide 2. slider 用了 JavaScript Library – Swiper 3. 当 slide active ...
- 第5天:基础入门-反弹SHELL&不回显带外&正反向连接&防火墙出入站&文件下载
文件上传下载-解决无图形化&解决数据传输 命令生成:https://forum.ywhack.com/bountytips.php?download 反弹shell 以参照物为准,以Linux ...
- crypt.h:No such file or directory 报错处理
crypt.h:No such file or directory 报错处理 前言:本文初编辑于2024年9月28日 CSDN主页:https://blog.csdn.net/rvdgdsva 博客园 ...
- 《Vue.js 设计与实现》读书笔记 - 第15章、编译器核心技术概览
第15章.编译器核心技术概览 15.1 模板 DSL 的编译器 完整的编译包括 [源代码] -->词法分析-->语法分析-->语义分析(编译前端) -->中间代码生成--> ...
- map&unordered_map<key,value>key使用自定义类的要求
std::unordered_map 的键要求: std::unordered_map 是基于哈希表的数据结构. 它要求键类型必须支持哈希计算,也就是必须有对应的 std::hash 函数. 另外,键 ...
- ARMv8中non-shareable inner-shareable outer-shareable属性
如果将block的内存属性配置成Non-cacheable,那么数据就不会被缓存到cache,那么所有observer看到的内存是一致的,也就说此时也相当于Outer Shareable. 其实官方文 ...
- nicegui太香了,跨平台开发和跨平台运行--使用Python+nicegui实现系统布局界面的开发
在现今国产化浪潮的驱动下,跨平台或者缩小范围说基于国产化Linux或者基于国产鸿蒙系统的开发才是未来的趋势了,风口浪尖上,我们开发人员也只能顺势而为,本篇随笔介绍在Python开发中,使用使用Pyth ...