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

golang之http请求库go-resty

时间:2023-06-15 19:33:28浏览次数:46  
标签:resty err fmt golang Println client 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,go
From: https://www.cnblogs.com/xingxia/p/golang_http_resty.html

相关文章

  • golang之errors包
    errors包常用方法funcUnwrap(errerror)error//获得err包含下一层错误funcIs(err,targeterror)bool//判断err是否包含targetfuncAs(errerror,targetinterface{})bool//判断err是否为target类型   自定义错误信息err......
  • GOTC峰会Sermant发布1.1.0-beta版本,带来哪些提升?
    5月27-28日,GOTC全球开源技术峰会在上海如约举办,Sermant也在GOTC中进行亮相,并参与了活动展台、快闪演讲等活动,吸引众多开发者深入了解Sermant的无代理微服务框架的非侵入、高性能、插件化的核心优势,并对探索实践和落地表现出极大兴趣。本次GOTC峰会也邀请了Linux基金会执行董事、LF......
  • Django中间件案例由浅入深+实战
    Django中间件案例由浅入深+实战原文链接:https://pfertyk.me/2020/04/getting-started-with-django-middleware/Django具有许多有用的功能特色,其中之一便是中间件。在本文中,我将简要解释中间件如何工作以及如何开始编写自己的中间件。这篇文章中包含的源代码可在GitHub上找到......
  • 解决mysql数据库 ‘ MySQL server has gone away’
    参考:https://www.jianshu.com/p/8c8086c11cae原因:查询的结果集超过max_allowed_packet查看执行SQL执行文件大小是否超过max_allowed_packet,如果超过则需要调整参数,或者优化语句。解决:修改参数,max_allowed_packet,比如调整为28M。要大于执行的SQL文件大小setglobalmax_a......
  • Google Test(GTest)和Google Mock(GMock)入门简介
    GoogleTest1.自定义错误输出:ASSERT_EQ(x.size(),y.size())<<"Vectorsxandyareofunequallength";for(inti=0;i<x.size();++i){EXPECT_EQ(x[i],y[i])<<"Vectorsxandydifferatindex"<<i;}2.ASSERT_......
  • 百度谷歌一起搜 - 百Google度 - Chrome插件2
    百度谷歌一起搜,我见过最好用的Chrome搜索插件。特此隆重推荐~ 谷歌百度一键搜索在Baidu里面搜Google,在Google里面搜百度!不用切换,松松搞定~~有图有真相:插件安装地址:http://t.cn/zWUv7wX插件安装地址:http://t.cn/zWUv7wX源码地址:https://github.com/raywill/BaiGoogleDu......
  • 百度谷歌一起搜 - 百Google度 - Chrome插件
    百度谷歌一起搜,我见过最好用的Chrome搜索插件。特此隆重推荐~ 谷歌百度一键搜索在Baidu里面搜Google,在Google里面搜百度!不用切换,松松搞定~~有图有真相:插件安装地址:http://t.cn/zWUv7wX插件安装地址:http://t.cn/zWUv7wX源码地址:https://github.com/raywill/BaiGoogleDu......
  • django 实现linux运维管理平台
    概述使用django实现一个linux运维管理平台,可以实现注册登录,机器管理,服务器批量操作,服务器性能监控。详细一、准备工作1、需要准备什么环境我是在自己的云服务上编写和运行的,centos7.2的环境,python是系统自带的python2.7.5,django安装的1.8.5版本的。数据库使用的mysql......
  • rocketmq-client-go
    关注几个配置项:topicgroupNametag按需配置即可。关于producer和consumer的入口启动略去,客户端层面,关于producer和consumer可以按照自己业务特点,进行配置。以下为simple样例。生产者1packageproducer23import(4"context"5"fmt"6"github.c......
  • docker-compose构建kratos微服务项目运行失败,提示:runtime/cgo: pthread_create failed
    这个问题网上解决方案较少,我们这边问题定位是docker-compose.yaml配置问题在配置文件中新增配置如下:privileged:true设置容器的权限为root 最后解决......