首页 > 其他分享 >golang之http请求库go-resty

golang之http请求库go-resty

时间:2023-07-05 13:31:42浏览次数:52  
标签:resty err fmt golang Println client https go

 

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!!!

 



标签:resty,err,fmt,golang,Println,client,https,go
From: https://blog.51cto.com/u_11045899/6631298

相关文章

  • Django 数据库操作
    查询models.UserInfo.objects.all()models.UserInfo.objects.all().values('user')#只取user列models.UserInfo.objects.all().values_list('id','user')#取出id和user列,并生成一个列表models.UserInfo.objects.get(id=1)models.UserInfo.objects.get(u......
  • 阿里云 MongoDB 创建库添加用户并授权
    先通过root进到admin库,右击test选择用户管理测试连接......
  • RunnerGo 新增对WebSocket、dubbo、TCP/IP三种协议的API测试
    大家好,RunnerGo作为一款一站式测试平台不断为用户提供更好的使用体验,最近得知RunnerGo新增对,WebSocket、Dubbo、TCP/IP,三种协议API的测试支持,本篇文章跟大家分享一下使用方法。WebSocket协议WebSocket是一种在单个TCP连接上进行全双工通信的API技术。相比于传统的HTTP......
  • Vue, Django | 数据可视化平台开发
    给公司搞了个互联网设备可视化平台,在地图上展示互联网设备的信息,点击地图不同区域,统计相应的设备信息,生成图表展示出来用的vue-big-screen框架,在原框架基础上,主要干了下面几件事:1.下载不同区域的geojson数据,点击大图的不同区域,调用mapclick方法,将子区域的geojson数据加载出来2......
  • Nginx+Uwsgi+Django+Mysql部署项目
    第一章、准备工作第1节、创建项目目录准备好项目代码,将代码上传至myprojectmkdirmyproject第2节、安装python3cd/usr/local/mkdirPythonwgethttps://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgztar-zxvfPython-3.8.0.tgzmkdir/usr/local/Python/py3_p......
  • go汇编语言-闭包是如何实现的?
    分析的代码packagemainfunctest(aint)func(iint)int{returnfunc(iint)int{a=a+ireturna}}funcmain(){f:=test(1)a:=f(2)println(a)b:=f(3)println(b)}代码比较简易,test函数产生一个闭包......
  • Google Guice 入门教程01 - 依赖注入
    1.依赖注入1.1类依赖注入所谓的绑定就是将一个接口绑定到具体的类中,这样客户端不用关心具体的实现,而只需要获取相应的接口完成其服务即可。HelloWorld.java 1publicinterfaceHelloWorld{23StringsayHello();4}5然后是具体的实现,HelloWorldImpl.j......
  • FreeWheel基于Go的实践经验漫谈——GC是大坑(关键业务场景不用),web框架尚未统一,和c++性
    Go语言是FreeWheel公司目前主要力推的一个方向,在其看来,面向服务的架构的大环境中,Go非常适合做一些功能相对独立、功能比较明确的微服务的语言。在结合已有的各种编程语言,计算框架(如Hadoop、Java、Ruby、C++)的基础上,FreeWheel把Go语言定位成用来实现轻量级服务或API的缺省编程语言,将......
  • A Go library implementing an FST (finite state transducer)——mark下
    https://github.com/couchbaselabs/vellumBuildinganFSTTobuildanFST,createanewbuilderusingthe New() method.Thismethodtakesan io.Writer asanargument.AstheFSTisbeingbuilt,datawillbestreamedtothewriterassoonaspossible.Withthi......
  • .Net下验证MongoDB 的 Linq 模式联合查询是否可用
    MongoDB.Driver类库提供了Linq查询的支持。然而,在使用Linq进行联合查询时,是否能够正确转换为MongoDB底层的查询语句还有待验证。今天,我将进行实验来验证一下。输出查询语句首先,通过订阅MongoClientSettings的功能,将查询语句输出。varsettings=MongoCli......