resty

package module
Version: v1.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 5, 2018 License: MIT Imports: 31 Imported by: 0

README

Resty

Simple HTTP and REST client library for Go (inspired by Ruby rest-client)

Features section describes in detail about Resty capabilities

Build Status Code Coverage Go Report Card Release Version GoDoc License

News

  • Collecting Inputs for Resty v2.0
  • v1.8.0 released and tagged on Aug 05, 2018.
  • v1.0 released - Resty's first version was released on Sep 15, 2015 then it grew gradually as a very handy and helpful library. Its been a two years; v1.0 was released on Sep 25, 2017. I'm very thankful to Resty users and its contributors.

Features

  • GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc.
  • Simple and chainable methods for settings and request
  • Request Body can be string, []byte, struct, map, slice and io.Reader too
    • Auto detects Content-Type
    • Buffer less processing for io.Reader
  • Response object gives you more possibility
    • Access as []byte array - response.Body() OR Access as string - response.String()
    • Know your response.Time() and when we response.ReceivedAt()
  • Automatic marshal and unmarshal for JSON and XML content type
  • Easy to upload one or more file(s) via multipart/form-data
    • Auto detects file content type
  • Request URL Path Params (aka URI Params)
  • Backoff Retry Mechanism with retry condition function reference
  • resty client HTTP & REST Request and Response middlewares
  • Request.SetContext supported go1.7 and above
  • Authorization option of BasicAuth and Bearer token
  • Set request ContentLength value for all request or particular request
  • Choose between HTTP and REST mode. Default is REST
    • HTTP - default up to 10 redirects and no automatic response unmarshal
    • REST - defaults to no redirects and automatic response marshal/unmarshal for JSON & XML
  • Custom Root Certificates and Client Certificates
  • Download/Save HTTP response directly into File, like curl -o flag. See SetOutputDirectory & SetOutput.
  • Cookies for your request and CookieJar support
  • SRV Record based request instead of Host URL
  • Client settings like Timeout, RedirectPolicy, Proxy, TLSClientConfig, Transport, etc.
  • Optionally allows GET request with payload, see SetAllowGetMethodPayload
  • Supports registering external JSON library into resty, see how to use
  • Exposes Response reader without reading response (no auto-unmarshaling) if need be, see how to use
  • Option to specify expected Content-Type when response Content-Type header missing. Refer to #92
  • Resty design
    • Have client level settings & options and also override at Request level if you want to
    • Request and Response middlewares
    • Create Multiple clients if you want to resty.New()
    • Supports http.RoundTripper implementation, see SetTransport
    • goroutine concurrent safe
    • REST and HTTP modes
    • Debug mode - clean and informative logging presentation
    • Gzip - Go does it automatically also resty has fallback handling too
    • Works fine with HTTP/2 and HTTP/1.1
  • Bazel support
  • Easily mock resty for testing, for e.g.
  • Well tested client library

Resty works with go1.3 and above.

Included Batteries

  • Redirect Policies - see how to use
    • NoRedirectPolicy
    • FlexibleRedirectPolicy
    • DomainCheckRedirectPolicy
    • etc. more info
  • Retry Mechanism how to use
    • Backoff Retry
    • Conditional Retry
  • SRV Record based request instead of Host URL how to use
  • etc (upcoming - throw your idea's here).

Installation

Stable Version - Production Ready

Please refer section Versioning for detailed info.

go.mod
require github.com/go-resty/resty v1.8.0
go get
go get -u gopkg.in/resty.v1
Latest Version - Development Edge
# install the latest & greatest library
go get -u github.com/go-resty/resty

It might be beneficial for your project 😄

Resty author also published following projects for Go Community.

  • aah framework - A secure, flexible, rapid Go web framework.
  • go-model - Robust & Easy to use model mapper and utility methods for Go struct.

Usage

The following samples will assist you to become as comfortable as possible with resty library. Resty comes with ready to use DefaultClient.

Import resty into your code and refer it as resty.

import "gopkg.in/resty.v1"
Simple GET
// GET request
resp, err := resty.R().Get("http://httpbin.org/get")

// explore response object
fmt.Printf("\nError: %v", err)
fmt.Printf("\nResponse Status Code: %v", resp.StatusCode())
fmt.Printf("\nResponse Status: %v", resp.Status())
fmt.Printf("\nResponse Time: %v", resp.Time())
fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt())
fmt.Printf("\nResponse Body: %v", resp)     // or resp.String() or string(resp.Body())
// more...

/* Output
Error: <nil>
Response Status Code: 200
Response Status: 200 OK
Response Time: 644.290186ms
Response Received At: 2015-09-15 12:05:28.922780103 -0700 PDT
Response Body: {
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Host": "httpbin.org",
    "User-Agent": "go-resty v0.1 - https://github.com/go-resty/resty"
  },
  "origin": "0.0.0.0",
  "url": "http://httpbin.org/get"
}
*/
Enhanced GET
resp, err := resty.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")


// Sample of using Request.SetQueryString method
resp, err := resty.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")
Various POST method combinations
// POST JSON string
// No need to set content type, if you have client level setting
resp, err := resty.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 setting
resp, err := resty.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 one
resp, err := resty.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 one
resp, err := resty.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 Dropbox
fileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf")

// See we are not setting content-type header, since go-resty automatically detects Content-Type for you
resp, err := resty.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
Sample PUT

You can use various combinations of PUT method call like demonstrated for POST.

// Note: This is one sample of PUT method usage, refer POST for more combination

// Request goes as JSON content type
// No need to set auth token, error, if you have client level settings
resp, err := resty.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")
Sample PATCH

You can use various combinations of PATCH method call like demonstrated for POST.

// Note: This is one sample of PUT method usage, refer POST for more combination

// Request goes as JSON content type
// No need to set auth token, error, if you have client level settings
resp, err := resty.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")
Sample DELETE, HEAD, OPTIONS
// DELETE a article
// No need to set auth token, error, if you have client level settings
resp, err := resty.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 settings
resp, err := resty.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 settings
resp, err := resty.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 settings
resp, err := resty.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      Options("https://myapp.com/servers/nyc-dc-01")

Multipart File(s) upload

Using io.Reader
profileImgBytes, _ := ioutil.ReadFile("/Users/jeeva/test-img.png")
notesBytes, _ := ioutil.ReadFile("/Users/jeeva/text-file.txt")

resp, err := dclr().
      SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)).
      SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)).
      SetFormData(map[string]string{
          "first_name": "Jeevanandam",
          "last_name": "M",
      }).
      Post(t"http://myapp.com/upload")
Using File directly from Path
// Single file scenario
resp, err := resty.R().
      SetFile("profile_img", "/Users/jeeva/test-img.png").
      Post("http://myapp.com/upload")

// Multiple files scenario
resp, err := resty.R().
      SetFiles(map[string]string{
        "profile_img": "/Users/jeeva/test-img.png",
        "notes": "/Users/jeeva/text-file.txt",
      }).
      Post("http://myapp.com/upload")

// Multipart of form fields and files
resp, err := resty.R().
      SetFiles(map[string]string{
        "profile_img": "/Users/jeeva/test-img.png",
        "notes": "/Users/jeeva/text-file.txt",
      }).
      SetFormData(map[string]string{
        "first_name": "Jeevanandam",
        "last_name": "M",
        "zip_code": "00001",
        "city": "my city",
        "access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD",
      }).
      Post("http://myapp.com/profile")
Sample Form submission
// just mentioning about POST as an example with simple flow
// User Login
resp, err := resty.R().
      SetFormData(map[string]string{
        "username": "jeeva",
        "password": "mypass",
      }).
      Post("http://myapp.com/login")

// Followed by profile update
resp, err := resty.R().
      SetFormData(map[string]string{
        "first_name": "Jeevanandam",
        "last_name": "M",
        "zip_code": "00001",
        "city": "new city update",
      }).
      Post("http://myapp.com/profile")

// Multi value form data
criteria := url.Values{
  "search_criteria": []string{"book", "glass", "pencil"},
}
resp, err := resty.R().
      SetMultiValueFormData(criteria).
      Post("http://myapp.com/search")
Save HTTP Response into File
// Setting output directory path, If directory not exists then resty creates one!
// This is optional one, if you're planning using absoule path in
// `Request.SetOutput` and can used together.
resty.SetOutputDirectory("/Users/jeeva/Downloads")

// HTTP response gets saved into file, similar to curl -o flag
_, err := resty.R().
          SetOutput("plugin/ReplyWithHeader-v5.1-beta.zip").
          Get("http://bit.ly/1LouEKr")

// OR using absolute path
// Note: output directory path is not used for absoulte path
_, err := resty.R().
          SetOutput("/MyDownloads/plugin/ReplyWithHeader-v5.1-beta.zip").
          Get("http://bit.ly/1LouEKr")
Request URL Path Params

Resty provides easy to use dynamic request URL path params. Params can be set at client and request level. Client level params value can be overridden at request level.

resty.R().SetPathParams(map[string]string{
   "userId": "sample@sample.com",
   "subAccountId": "100002",
}).
Get("/v1/users/{userId}/{subAccountId}/details")

// Result:
//   Composed URL - /v1/users/sample@sample.com/100002/details
Request and Response Middleware

Resty provides middleware ability to manipulate for Request and Response. It is more flexible than callback approach.

// Registering Request Middleware
resty.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 Middleware
resty.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
  })
Redirect Policy

Resty provides few ready to use redirect policy(s) also it supports multiple policies together.

// Assign Client Redirect Policy. Create one as per you need
resty.SetRedirectPolicy(resty.FlexibleRedirectPolicy(15))

// Wanna multiple policies such as redirect count, domain name check, etc
resty.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20),
                        resty.DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))
Custom Redirect Policy

Implement RedirectPolicy interface and register it with resty client. Have a look redirect.go for more information.

// Using raw func into resty.SetRedirectPolicy
resty.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
  // Implement your logic here

  // return nil for continue redirect otherwise return error to stop/prevent redirect
  return nil
}))

//---------------------------------------------------

// Using struct create more flexible redirect policy
type CustomRedirectPolicy struct {
  // variables goes here
}

func (c *CustomRedirectPolicy) Apply(req *http.Request, via []*http.Request) error {
  // Implement your logic here

  // return nil for continue redirect otherwise return error to stop/prevent redirect
  return nil
}

// Registering in resty
resty.SetRedirectPolicy(CustomRedirectPolicy{/* initialize variables */})
Custom Root Certificates and Client Certificates
// Custom Root certificates, just supply .pem file.
// you can add one or more root certificates, its get appended
resty.SetRootCertificate("/path/to/root/pemFile1.pem")
resty.SetRootCertificate("/path/to/root/pemFile2.pem")
// ... and so on!

// Adding Client Certificates, you add one or more certificates
// Sample for creating certificate object
// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
cert1, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
if err != nil {
  log.Fatalf("ERROR client certificate: %s", err)
}
// ...

// You add one or more certificates
resty.SetCertificates(cert1, cert2, cert3)
Proxy Settings - Client as well as at Request Level

Default Go supports Proxy via environment variable HTTP_PROXY. Resty provides support via SetProxy & RemoveProxy. Choose as per your need.

Client Level Proxy settings applied to all the request

// Setting a Proxy URL and Port
resty.SetProxy("http://proxyserver:8888")

// Want to remove proxy setting
resty.RemoveProxy()
Retries

Resty uses backoff to increase retry intervals after each attempt.

Usage example:

// Retries are configured per client
resty.
    // 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)

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:

resty.AddRetryCondition(
    // Condition function will be provided with *resty.Response as a
    // parameter. It is expected to return (bool, error) pair. Resty will retry
    // in case condition returns true or non nil error.
    func(r *resty.Response) (bool, error) {
        return r.StatusCode() == http.StatusTooManyRequests, nil
    },
)

Above example will make resty retry requests ended with 429 Too Many Requests status code.

Multiple retry conditions can be added.

It is also possible to use resty.Backoff(...) to get arbitrary retry scenarios implemented. Reference.

Choose REST or HTTP mode
// REST mode. This is Default.
resty.SetRESTMode()

// HTTP mode
resty.SetHTTPMode()
Allow GET request with Payload
// Allow GET request with Payload. This is disabled by default.
resty.SetAllowGetMethodPayload(true)
Wanna Multiple Clients
// Here you go!
// Client 1
client1 := resty.New()
client1.R().Get("http://httpbin.org")
// ...

// Client 2
client2 := resty.New()
client2.R().Head("http://httpbin.org")
// ...

// Bend it as per your need!!!
Remaining Client Settings & its Options
// Unique settings at Client level
//--------------------------------
// Enable debug mode
resty.SetDebug(true)

// Using you custom log writer
logFile, _ := os.OpenFile("/Users/jeeva/go-resty.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
resty.SetLogger(logFile)

// Assign Client TLSClientConfig
// One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial
resty.SetTLSClientConfig(&tls.Config{ RootCAs: roots })

// or One can disable security check (https)
resty.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })

// Set client timeout as per your need
resty.SetTimeout(1 * time.Minute)


// You can override all below settings and options at request level if you want to
//--------------------------------------------------------------------------------
// Host URL for all request. So you can use relative URL in the request
resty.SetHostURL("http://httpbin.org")

// Headers for all request
resty.SetHeader("Accept", "application/json")
resty.SetHeaders(map[string]string{
        "Content-Type": "application/json",
        "User-Agent": "My custom User Agent String",
      })

// Cookies for all request
resty.SetCookie(&http.Cookie{
      Name:"go-resty",
      Value:"This is cookie value",
      Path: "/",
      Domain: "sample.com",
      MaxAge: 36000,
      HttpOnly: true,
      Secure: false,
    })
resty.SetCookies(cookies)

// URL query parameters for all request
resty.SetQueryParam("user_id", "00001")
resty.SetQueryParams(map[string]string{ // sample of those who use this manner
      "api_key": "api-key-here",
      "api_secert": "api-secert",
    })
resty.R().SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")

// Form data for all request. Typically used with POST and PUT
resty.SetFormData(map[string]string{
    "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
  })

// Basic Auth for all request
resty.SetBasicAuth("myuser", "mypass")

// Bearer Auth Token for all request
resty.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")

// Enabling Content length value for all request
resty.SetContentLength(true)

// Registering global Error object structure for JSON/XML request
resty.SetError(&Error{})    // or resty.SetError(Error{})
Unix Socket
unixSocket := "/var/run/my_socket.sock"

// Create a Go's http.Transport so we can set it in resty.
transport := http.Transport{
	Dial: func(_, _ string) (net.Conn, error) {
		return net.Dial("unix", unixSocket)
	},
}

// Set the previous transport that we created, set the scheme of the communication to the
// socket and set the unixSocket as the HostURL.
r := resty.New().SetTransport(&transport).SetScheme("http").SetHostURL(unixSocket)

// No need to write the host's URL on the request, just the path.
r.R().Get("/index.html")
Bazel support

Resty can be built, tested and depended upon via Bazel. For example, to run all tests:

bazel test :go_default_test
Mocking http requests using httpmock library

In order to mock the http requests when testing your application you could use the httpmock library.

When using the default resty client, you should pass the client to the library as follow:

httpmock.ActivateNonDefault(resty.DefaultClient.GetClient())

More detailed example of mocking resty http requests using ginko could be found here.

Versioning

resty releases versions according to Semantic Versioning

  • gopkg.in/resty.vX points to appropriate tagged versions; X denotes version series number and it's a stable release for production use. For e.g. gopkg.in/resty.v0.
  • Development takes place at the master branch. Although the code in master should always compile and test successfully, it might break API's. I aim to maintain backwards compatibility, but sometimes API's and behavior might be changed to fix a bug.

Contribution

I would welcome your contribution! If you find any improvement or issue you want to fix, feel free to send a pull request, I like pull requests that include test cases for fix/enhancement. I have done my best to bring pretty good code coverage. Feel free to write tests.

BTW, I'd like to know what you think about Resty. Kindly open an issue or send me an email; it'd mean a lot to me.

Creator

Jeevanandam M. (jeeva@myjeeva.com)

Contributors

Have a look on Contributors page.

License

Resty released under MIT license, refer LICENSE file.

Documentation

Overview

Package resty provides simple HTTP and REST client for Go inspired by Ruby rest-client.

Example (ClientCertificates)
package main

import (
	"crypto/tls"
	"log"

	"github.com/go-resty/resty"
)

func main() {
	// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
	cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
	if err != nil {
		log.Fatalf("ERROR client certificate: %s", err)
	}

	resty.SetCertificates(cert)
}
Output:

Example (CustomRootCertificate)
package main

import (
	"github.com/go-resty/resty"
)

func main() {
	resty.SetRootCertificate("/path/to/root/pemFile.pem")
}
Output:

Example (DropboxUpload)
package main

import (
	"fmt"
	"io/ioutil"
	"os"

	"github.com/go-resty/resty"
)

type DropboxError struct {
	Error string
}

func main() {
	// For example: upload file to Dropbox
	// POST of raw bytes for file upload.
	file, _ := os.Open("/Users/jeeva/mydocument.pdf")
	fileBytes, _ := ioutil.ReadAll(file)

	// See we are not setting content-type header, since go-resty automatically detects Content-Type for you
	resp, err := resty.R().
		SetBody(fileBytes).     // resty autodetects content type
		SetContentLength(true). // Dropbox expects this value
		SetAuthToken("<your-auth-token>").
		SetError(DropboxError{}).
		Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // you can use PUT method too dropbox supports it

	// Output print
	fmt.Printf("\nError: %v\n", err)
	fmt.Printf("Time: %v\n", resp.Time())
	fmt.Printf("Body: %v\n", resp)
}
Output:

Example (EnhancedGet)
package main

import (
	"fmt"
	"strconv"
	"time"

	"github.com/go-resty/resty"
)

func main() {
	resp, err := resty.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")

	printOutput(resp, err)
}

func printOutput(resp *resty.Response, err error) {
	fmt.Println(resp, err)
}
Output:

Example (Get)
package main

import (
	"fmt"

	"github.com/go-resty/resty"
)

func main() {
	resp, err := resty.R().Get("http://httpbin.org/get")

	fmt.Printf("\nError: %v", err)
	fmt.Printf("\nResponse Status Code: %v", resp.StatusCode())
	fmt.Printf("\nResponse Status: %v", resp.Status())
	fmt.Printf("\nResponse Body: %v", resp)
	fmt.Printf("\nResponse Time: %v", resp.Time())
	fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt())
}
Output:

Example (Post)
package main

import (
	"fmt"

	"github.com/go-resty/resty"
)

type AuthSuccess struct {
}
type AuthError struct {
}

func main() {
	// POST JSON string
	// No need to set content type, if you have client level setting
	resp, err := resty.R().
		SetHeader("Content-Type", "application/json").
		SetBody(`{"username":"testuser", "password":"testpass"}`).
		SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}).
		Post("https://myapp.com/login")

	printOutput(resp, err)

	// POST []byte array
	// No need to set content type, if you have client level setting
	resp1, err1 := resty.R().
		SetHeader("Content-Type", "application/json").
		SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
		SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}).
		Post("https://myapp.com/login")

	printOutput(resp1, err1)

	// POST Struct, default is JSON content type. No need to set one
	resp2, err2 := resty.R().
		SetBody(resty.User{Username: "testuser", Password: "testpass"}).
		SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
		SetError(&AuthError{}).    // or SetError(AuthError{}).
		Post("https://myapp.com/login")

	printOutput(resp2, err2)

	// POST Map, default is JSON content type. No need to set one
	resp3, err3 := resty.R().
		SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
		SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
		SetError(&AuthError{}).    // or SetError(AuthError{}).
		Post("https://myapp.com/login")

	printOutput(resp3, err3)
}

func printOutput(resp *resty.Response, err error) {
	fmt.Println(resp, err)
}
Output:

Example (Put)
package main

import (
	"fmt"

	"github.com/go-resty/resty"
)

type Article struct {
	Title   string
	Content string
	Author  string
	Tags    []string
}
type Error struct {
}

func main() {
	// Just one sample of PUT, refer POST for more combination
	// request goes as JSON content type
	// No need to set auth token, error, if you have client level settings
	resp, err := resty.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")

	printOutput(resp, err)
}

func printOutput(resp *resty.Response, err error) {
	fmt.Println(resp, err)
}
Output:

Example (Socks5Proxy)
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/go-resty/resty"
	"golang.org/x/net/proxy"
)

func main() {
	// create a dialer
	dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:9150", nil, proxy.Direct)
	if err != nil {
		log.Fatalf("Unable to obtain proxy dialer: %v\n", err)
	}

	// create a transport
	ptransport := &http.Transport{Dial: dialer.Dial}

	// set transport into resty
	resty.SetTransport(ptransport)

	resp, err := resty.R().Get("http://check.torproject.org")
	fmt.Println(err, resp)
}
Output:

Index

Examples

Constants

View Source
const (
	// MethodGet HTTP method
	MethodGet = "GET"

	// MethodPost HTTP method
	MethodPost = "POST"

	// MethodPut HTTP method
	MethodPut = "PUT"

	// MethodDelete HTTP method
	MethodDelete = "DELETE"

	// MethodPatch HTTP method
	MethodPatch = "PATCH"

	// MethodHead HTTP method
	MethodHead = "HEAD"

	// MethodOptions HTTP method
	MethodOptions = "OPTIONS"
)
View Source
const Version = "1.8.0"

Version # of resty

Variables

This section is empty.

Functions

func Backoff added in v1.7.0

func Backoff(operation func() (*Response, error), options ...Option) error

Backoff retries with increasing timeout duration up until X amount of retries (Default is 3 attempts, Override with option Retries(n))

func DetectContentType

func DetectContentType(body interface{}) string

DetectContentType method is used to figure out `Request.Body` content type for request header

func GetClient added in v1.7.0

func GetClient() *http.Client

GetClient method returns the current `http.Client` used by the default resty client.

func IsJSONType

func IsJSONType(ct string) bool

IsJSONType method is to check JSON content type or not

func IsProxySet added in v1.7.0

func IsProxySet() bool

IsProxySet method returns the true if proxy is set on client otherwise false. See `Client.IsProxySet` for more information.

func IsStringEmpty

func IsStringEmpty(str string) bool

IsStringEmpty method tells whether given string is empty or not

func IsXMLType

func IsXMLType(ct string) bool

IsXMLType method is to check XML content type or not

func Mode

func Mode() string

Mode method returns the current client mode. See `Client.Mode` for more information.

func Unmarshal deprecated

func Unmarshal(ct string, b []byte, d interface{}) (err error)

Unmarshal content into object from JSON or XML Deprecated: kept for backward compatibility

func Unmarshalc added in v1.7.0

func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error)

Unmarshalc content into object from JSON or XML

Types

type Client

type Client struct {
	HostURL               string
	QueryParam            url.Values
	FormData              url.Values
	Header                http.Header
	UserInfo              *User
	Token                 string
	Cookies               []*http.Cookie
	Error                 reflect.Type
	Debug                 bool
	DisableWarn           bool
	AllowGetMethodPayload bool
	Log                   *log.Logger
	RetryCount            int
	RetryWaitTime         time.Duration
	RetryMaxWaitTime      time.Duration
	RetryConditions       []RetryConditionFunc
	JSONMarshal           func(v interface{}) ([]byte, error)
	JSONUnmarshal         func(data []byte, v interface{}) error
	// contains filtered or unexported fields
}

Client type is used for HTTP/RESTful global values for all request raised from the client

var DefaultClient *Client

DefaultClient of resty

func AddRetryCondition added in v1.7.0

func AddRetryCondition(condition RetryConditionFunc) *Client

AddRetryCondition method appends check function for retry. See `Client.AddRetryCondition` for more information.

func New

func New() *Client

New method creates a new go-resty client.

Example
package main

import (
	"fmt"

	"github.com/go-resty/resty"
)

func main() {
	// Creating client1
	client1 := resty.New()
	resp1, err1 := client1.R().Get("http://httpbin.org/get")
	fmt.Println(resp1, err1)

	// Creating client2
	client2 := resty.New()
	resp2, err2 := client2.R().Get("http://httpbin.org/get")
	fmt.Println(resp2, err2)
}
Output:

func NewWithClient added in v1.7.0

func NewWithClient(hc *http.Client) *Client

NewWithClient method create a new go-resty client with given `http.Client`.

func OnAfterResponse

func OnAfterResponse(m func(*Client, *Response) error) *Client

OnAfterResponse method sets response middleware. See `Client.OnAfterResponse` for more information.

func OnBeforeRequest

func OnBeforeRequest(m func(*Client, *Request) error) *Client

OnBeforeRequest method sets request middleware. See `Client.OnBeforeRequest` for more information.

func RemoveProxy

func RemoveProxy() *Client

RemoveProxy method removes the proxy configuration. See `Client.RemoveProxy` for more information.

func SetAllowGetMethodPayload added in v1.7.0

func SetAllowGetMethodPayload(a bool) *Client

SetAllowGetMethodPayload method allows the GET method with payload. See `Client.SetAllowGetMethodPayload` for more information.

func SetAuthToken

func SetAuthToken(token string) *Client

SetAuthToken method sets bearer auth token header. See `Client.SetAuthToken` for more information.

func SetBasicAuth

func SetBasicAuth(username, password string) *Client

SetBasicAuth method sets the basic authentication header. See `Client.SetBasicAuth` for more information.

func SetCertificates added in v0.4.1

func SetCertificates(certs ...tls.Certificate) *Client

SetCertificates method helps to set client certificates into resty conveniently. See `Client.SetCertificates` for more information and example.

func SetCloseConnection added in v1.7.0

func SetCloseConnection(close bool) *Client

SetCloseConnection method sets close connection value in the resty client. See `Client.SetCloseConnection` for more information.

func SetContentLength

func SetContentLength(l bool) *Client

SetContentLength method enables `Content-Length` value. See `Client.SetContentLength` for more information.

func SetCookie

func SetCookie(hc *http.Cookie) *Client

SetCookie sets single cookie object. See `Client.SetCookie` for more information.

func SetCookieJar added in v1.7.0

func SetCookieJar(jar http.CookieJar) *Client

SetCookieJar sets custom http.CookieJar. See `Client.SetCookieJar` for more information.

func SetCookies

func SetCookies(cs []*http.Cookie) *Client

SetCookies sets multiple cookie object. See `Client.SetCookies` for more information.

func SetDebug

func SetDebug(d bool) *Client

SetDebug method enables the debug mode. See `Client.SetDebug` for more information.

func SetDebugBodyLimit added in v1.7.0

func SetDebugBodyLimit(sl int64) *Client

SetDebugBodyLimit method sets the response body limit for debug mode. See `Client.SetDebugBodyLimit` for more information.

func SetDisableWarn added in v1.7.0

func SetDisableWarn(d bool) *Client

SetDisableWarn method disables warning comes from `go-resty` client. See `Client.SetDisableWarn` for more information.

func SetDoNotParseResponse added in v1.7.0

func SetDoNotParseResponse(parse bool) *Client

SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. See `Client.SetDoNotParseResponse` for more information.

func SetError

func SetError(err interface{}) *Client

SetError method is to register the global or client common `Error` object. See `Client.SetError` for more information.

func SetFormData

func SetFormData(data map[string]string) *Client

SetFormData method sets Form parameters and its values. See `Client.SetFormData` for more information.

func SetHTTPMode

func SetHTTPMode() *Client

SetHTTPMode method sets go-resty mode into HTTP. See `Client.SetMode` for more information.

func SetHeader

func SetHeader(header, value string) *Client

SetHeader sets single header. See `Client.SetHeader` for more information.

func SetHeaders

func SetHeaders(headers map[string]string) *Client

SetHeaders sets multiple headers. See `Client.SetHeaders` for more information.

func SetHostURL

func SetHostURL(url string) *Client

SetHostURL sets Host URL. See `Client.SetHostURL for more information.

func SetLogger

func SetLogger(w io.Writer) *Client

SetLogger method sets given writer for logging. See `Client.SetLogger` for more information.

func SetOutputDirectory added in v0.4.1

func SetOutputDirectory(dirPath string) *Client

SetOutputDirectory method sets output directory. See `Client.SetOutputDirectory` for more information.

func SetPathParams added in v1.7.0

func SetPathParams(params map[string]string) *Client

SetPathParams method sets the Request path parameter key-value pairs. See `Client.SetPathParams` for more information.

func SetPreRequestHook added in v1.7.0

func SetPreRequestHook(h func(*Client, *Request) error) *Client

SetPreRequestHook method sets the pre-request hook. See `Client.SetPreRequestHook` for more information.

func SetProxy

func SetProxy(proxyURL string) *Client

SetProxy method sets Proxy for request. See `Client.SetProxy` for more information.

func SetQueryParam

func SetQueryParam(param, value string) *Client

SetQueryParam method sets single parameter and its value. See `Client.SetQueryParam` for more information.

func SetQueryParams

func SetQueryParams(params map[string]string) *Client

SetQueryParams method sets multiple parameters and its value. See `Client.SetQueryParams` for more information.

func SetRESTMode

func SetRESTMode() *Client

SetRESTMode method sets go-resty mode into RESTful. See `Client.SetMode` for more information.

func SetRedirectPolicy

func SetRedirectPolicy(policies ...interface{}) *Client

SetRedirectPolicy method sets the client redirect poilicy. See `Client.SetRedirectPolicy` for more information.

func SetRetryCount added in v1.7.0

func SetRetryCount(count int) *Client

SetRetryCount method sets the retry count. See `Client.SetRetryCount` for more information.

func SetRetryMaxWaitTime added in v1.7.0

func SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client

SetRetryMaxWaitTime method sets the retry max wait time. See `Client.SetRetryMaxWaitTime` for more information.

func SetRetryWaitTime added in v1.7.0

func SetRetryWaitTime(waitTime time.Duration) *Client

SetRetryWaitTime method sets the retry wait time. See `Client.SetRetryWaitTime` for more information.

func SetRootCertificate added in v0.4.1

func SetRootCertificate(pemFilePath string) *Client

SetRootCertificate method helps to add one or more root certificates into resty client. See `Client.SetRootCertificate` for more information.

func SetScheme added in v1.7.0

func SetScheme(scheme string) *Client

SetScheme method sets custom scheme in the resty client. See `Client.SetScheme` for more information.

func SetTLSClientConfig

func SetTLSClientConfig(config *tls.Config) *Client

SetTLSClientConfig method sets TLSClientConfig for underling client Transport. See `Client.SetTLSClientConfig` for more information.

func SetTimeout

func SetTimeout(timeout time.Duration) *Client

SetTimeout method sets timeout for request. See `Client.SetTimeout` for more information.

func SetTransport added in v1.7.0

func SetTransport(transport http.RoundTripper) *Client

SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` compatible interface implementation in the resty client. See `Client.SetTransport` for more information.

func (*Client) AddRetryCondition added in v1.7.0

func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client

AddRetryCondition method adds a retry condition function to array of functions that are checked to determine if the request is retried. The request will retry if any of the functions return true and error is nil.

func (*Client) GetClient added in v1.7.0

func (c *Client) GetClient() *http.Client

GetClient method returns the current http.Client used by the resty client.

func (*Client) IsProxySet added in v1.7.0

func (c *Client) IsProxySet() bool

IsProxySet method returns the true if proxy is set on client otherwise false.

func (*Client) Mode

func (c *Client) Mode() string

Mode method returns the current client mode. Typically its a "http" or "rest". Default is "rest"

func (*Client) NewRequest added in v1.7.0

func (c *Client) NewRequest() *Request

NewRequest is an alias for R(). Creates a request instance, its used for Get, Post, Put, Delete, Patch, Head and Options.

func (*Client) OnAfterResponse

func (c *Client) OnAfterResponse(m func(*Client, *Response) error) *Client

OnAfterResponse method appends response middleware into the after response chain. Once we receive response from host server, default `go-resty` response middleware gets applied and then user assigened response middlewares applied.

resty.OnAfterResponse(func(c *resty.Client, r *resty.Response) error {
		// Now you have access to Client and Response instance
		// manipulate it as per your need

		return nil 	// if its success otherwise return error
	})

func (*Client) OnBeforeRequest

func (c *Client) OnBeforeRequest(m func(*Client, *Request) error) *Client

OnBeforeRequest method appends request middleware into the before request chain. Its gets applied after default `go-resty` request middlewares and before request been sent from `go-resty` to host server.

resty.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error {
		// Now you have access to Client and Request instance
		// manipulate it as per your need

		return nil 	// if its success otherwise return error
	})

func (*Client) R

func (c *Client) R() *Request

R method creates a request instance, its used for Get, Post, Put, Delete, Patch, Head and Options.

func (*Client) RemoveProxy

func (c *Client) RemoveProxy() *Client

RemoveProxy method removes the proxy configuration from resty client

resty.RemoveProxy()

func (*Client) SetAllowGetMethodPayload added in v1.7.0

func (c *Client) SetAllowGetMethodPayload(a bool) *Client

SetAllowGetMethodPayload method allows the GET method with payload on `go-resty` client. For example: go-resty allows the user sends request with a payload on HTTP GET method.

resty.SetAllowGetMethodPayload(true)

func (*Client) SetAuthToken

func (c *Client) SetAuthToken(token string) *Client

SetAuthToken method sets bearer auth token header in the HTTP request. Example:

Authorization: Bearer <auth-token-value-comes-here>

Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F

resty.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")

This bearer auth token gets added to all the request rasied from this client instance. Also it can be overridden or set one at the request level is supported, see `resty.R().SetAuthToken`.

func (*Client) SetBasicAuth

func (c *Client) SetBasicAuth(username, password string) *Client

SetBasicAuth method sets the basic authentication header in the HTTP request. Example:

Authorization: Basic <base64-encoded-value>

Example: To set the header for username "go-resty" and password "welcome"

resty.SetBasicAuth("go-resty", "welcome")

This basic auth information gets added to all the request rasied from this client instance. Also it can be overridden or set one at the request level is supported, see `resty.R().SetBasicAuth`.

func (*Client) SetCertificates added in v0.4.1

func (c *Client) SetCertificates(certs ...tls.Certificate) *Client

SetCertificates method helps to set client certificates into resty conveniently.

Example
package main

import (
	"crypto/tls"
	"log"

	"github.com/go-resty/resty"
)

func main() {
	// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
	cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
	if err != nil {
		log.Fatalf("ERROR client certificate: %s", err)
	}

	resty.SetCertificates(cert)
}
Output:

func (*Client) SetCloseConnection added in v1.7.0

func (c *Client) SetCloseConnection(close bool) *Client

SetCloseConnection method sets variable `Close` in http request struct with the given value. More info: https://golang.org/src/net/http/request.go

func (*Client) SetContentLength

func (c *Client) SetContentLength(l bool) *Client

SetContentLength method enables the HTTP header `Content-Length` value for every request. By default go-resty won't set `Content-Length`.

resty.SetContentLength(true)

Also you have an option to enable for particular request. See `resty.R().SetContentLength`

func (*Client) SetCookie

func (c *Client) SetCookie(hc *http.Cookie) *Client

SetCookie method appends a single cookie in the client instance. These cookies will be added to all the request raised from this client instance.

resty.SetCookie(&http.Cookie{
			Name:"go-resty",
			Value:"This is cookie value",
			Path: "/",
			Domain: "sample.com",
			MaxAge: 36000,
			HttpOnly: true,
			Secure: false,
		})

func (*Client) SetCookieJar added in v1.7.0

func (c *Client) SetCookieJar(jar http.CookieJar) *Client

SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default. Example: sometimes we don't want to save cookies in api contacting, we can remove the default CookieJar in resty client.

resty.SetCookieJar(nil)

func (*Client) SetCookies

func (c *Client) SetCookies(cs []*http.Cookie) *Client

SetCookies method sets an array of cookies in the client instance. These cookies will be added to all the request raised from this client instance.

cookies := make([]*http.Cookie, 0)

cookies = append(cookies, &http.Cookie{
			Name:"go-resty-1",
			Value:"This is cookie 1 value",
			Path: "/",
			Domain: "sample.com",
			MaxAge: 36000,
			HttpOnly: true,
			Secure: false,
		})

cookies = append(cookies, &http.Cookie{
			Name:"go-resty-2",
			Value:"This is cookie 2 value",
			Path: "/",
			Domain: "sample.com",
			MaxAge: 36000,
			HttpOnly: true,
			Secure: false,
		})

// Setting a cookies into resty
resty.SetCookies(cookies)

func (*Client) SetDebug

func (c *Client) SetDebug(d bool) *Client

SetDebug method enables the debug mode on `go-resty` client. Client logs details of every request and response. For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. For `Response` it logs information such as Status, Response Time, Headers, Body if it has one.

resty.SetDebug(true)

func (*Client) SetDebugBodyLimit added in v1.7.0

func (c *Client) SetDebugBodyLimit(sl int64) *Client

SetDebugBodyLimit sets the maximum size for which the response body will be logged in debug mode.

resty.SetDebugBodyLimit(1000000)

func (*Client) SetDisableWarn added in v1.7.0

func (c *Client) SetDisableWarn(d bool) *Client

SetDisableWarn method disables the warning message on `go-resty` client. For example: go-resty warns the user when BasicAuth used on HTTP mode.

resty.SetDisableWarn(true)

func (*Client) SetDoNotParseResponse added in v1.7.0

func (c *Client) SetDoNotParseResponse(parse bool) *Client

SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, otherwise you might get into connection leaks, no connection reuse.

Please Note: Response middlewares are not applicable, if you use this option. Basically you have taken over the control of response parsing from `Resty`.

func (*Client) SetError

func (c *Client) SetError(err interface{}) *Client

SetError method is to register the global or client common `Error` object into go-resty. It is used for automatic unmarshalling if response status code is greater than 399 and content type either JSON or XML. Can be pointer or non-pointer.

resty.SetError(&Error{})
// OR
resty.SetError(Error{})

func (*Client) SetFormData

func (c *Client) SetFormData(data map[string]string) *Client

SetFormData method sets Form parameters and their values in the client instance. It's applicable only HTTP method `POST` and `PUT` and requets content type would be set as `application/x-www-form-urlencoded`. These form data will be added to all the request raised from this client instance. Also it can be overridden at request level form data, see `resty.R().SetFormData`.

resty.SetFormData(map[string]string{
		"access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
		"user_id": "3455454545",
	})

func (*Client) SetHTTPMode

func (c *Client) SetHTTPMode() *Client

SetHTTPMode method sets go-resty mode to 'http'

func (*Client) SetHeader

func (c *Client) SetHeader(header, value string) *Client

SetHeader method sets a single header field and its value in the client instance. These headers will be applied to all requests raised from this client instance. Also it can be overridden at request level header options, see `resty.R().SetHeader` or `resty.R().SetHeaders`.

Example: To set `Content-Type` and `Accept` as `application/json`

resty.
	SetHeader("Content-Type", "application/json").
	SetHeader("Accept", "application/json")

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string) *Client

SetHeaders method sets multiple headers field and its values at one go in the client instance. These headers will be applied to all requests raised from this client instance. Also it can be overridden at request level headers options, see `resty.R().SetHeaders` or `resty.R().SetHeader`.

Example: To set `Content-Type` and `Accept` as `application/json`

resty.SetHeaders(map[string]string{
		"Content-Type": "application/json",
		"Accept": "application/json",
	})

func (*Client) SetHostURL

func (c *Client) SetHostURL(url string) *Client

SetHostURL method is to set Host URL in the client instance. It will be used with request raised from this client with relative URL

// Setting HTTP address
resty.SetHostURL("http://myjeeva.com")

// Setting HTTPS address
resty.SetHostURL("https://myjeeva.com")

func (*Client) SetLogPrefix added in v1.7.0

func (c *Client) SetLogPrefix(prefix string) *Client

SetLogPrefix method sets the Resty logger prefix value.

func (*Client) SetLogger

func (c *Client) SetLogger(w io.Writer) *Client

SetLogger method sets given writer for logging go-resty request and response details. Default is os.Stderr

file, _ := os.OpenFile("/Users/jeeva/go-resty.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

resty.SetLogger(file)

func (*Client) SetMode

func (c *Client) SetMode(mode string) *Client

SetMode method sets go-resty client mode to given value such as 'http' & 'rest'.

'rest':
	- No Redirect
	- Automatic response unmarshal if it is JSON or XML
'http':
	- Up to 10 Redirects
	- No automatic unmarshall. Response will be treated as `response.String()`

If you want more redirects, use FlexibleRedirectPolicy

resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))

func (*Client) SetOutputDirectory added in v0.4.1

func (c *Client) SetOutputDirectory(dirPath string) *Client

SetOutputDirectory method sets output directory for saving HTTP response into file. If the output directory not exists then resty creates one. This setting is optional one, if you're planning using absoule path in `Request.SetOutput` and can used together.

resty.SetOutputDirectory("/save/http/response/here")

func (*Client) SetPathParams added in v1.7.0

func (c *Client) SetPathParams(params map[string]string) *Client

SetPathParams method sets multiple URL path key-value pairs at one go in the resty client instance.

resty.SetPathParams(map[string]string{
   "userId": "sample@sample.com",
   "subAccountId": "100002",
})

Result:
   URL - /v1/users/{userId}/{subAccountId}/details
   Composed URL - /v1/users/sample@sample.com/100002/details

It replace the value of the key while composing request URL. Also it can be overridden at request level Path Params options, see `Request.SetPathParams`.

func (*Client) SetPreRequestHook added in v1.7.0

func (c *Client) SetPreRequestHook(h func(*Client, *Request) error) *Client

SetPreRequestHook method sets the given pre-request function into resty client. It is called right before the request is fired.

Note: Only one pre-request hook can be registered. Use `resty.OnBeforeRequest` for mutilple.

func (*Client) SetProxy

func (c *Client) SetProxy(proxyURL string) *Client

SetProxy method sets the Proxy URL and Port for resty client.

resty.SetProxy("http://proxyserver:8888")

Alternatives: At request level proxy, see `Request.SetProxy`. OR Without this `SetProxy` method, you can also set Proxy via environment variable. By default `Go` uses setting from `HTTP_PROXY`.

func (*Client) SetQueryParam

func (c *Client) SetQueryParam(param, value string) *Client

SetQueryParam method sets single parameter and its value in the client instance. It will be formed as query string for the request. For example: `search=kitchen%20papers&size=large` in the URL after `?` mark. These query params will be added to all the request raised from this client instance. Also it can be overridden at request level Query Param options, see `resty.R().SetQueryParam` or `resty.R().SetQueryParams`.

resty.
	SetQueryParam("search", "kitchen papers").
	SetQueryParam("size", "large")

func (*Client) SetQueryParams

func (c *Client) SetQueryParams(params map[string]string) *Client

SetQueryParams method sets multiple parameters and their values at one go in the client instance. It will be formed as query string for the request. For example: `search=kitchen%20papers&size=large` in the URL after `?` mark. These query params will be added to all the request raised from this client instance. Also it can be overridden at request level Query Param options, see `resty.R().SetQueryParams` or `resty.R().SetQueryParam`.

resty.SetQueryParams(map[string]string{
		"search": "kitchen papers",
		"size": "large",
	})

func (*Client) SetRESTMode

func (c *Client) SetRESTMode() *Client

SetRESTMode method sets go-resty mode to 'rest'

func (*Client) SetRedirectPolicy

func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client

SetRedirectPolicy method sets the client redirect poilicy. go-resty provides ready to use redirect policies. Wanna create one for yourself refer `redirect.go`.

resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))

// Need multiple redirect policies together
resty.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net"))

func (*Client) SetRetryCount added in v1.7.0

func (c *Client) SetRetryCount(count int) *Client

SetRetryCount method enables retry on `go-resty` client and allows you to set no. of retry count. Resty uses a Backoff mechanism.

func (*Client) SetRetryMaxWaitTime added in v1.7.0

func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client

SetRetryMaxWaitTime method sets max wait time to sleep before retrying request. Default is 2 seconds.

func (*Client) SetRetryWaitTime added in v1.7.0

func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client

SetRetryWaitTime method sets default wait time to sleep before retrying request. Default is 100 milliseconds.

func (*Client) SetRootCertificate added in v0.4.1

func (c *Client) SetRootCertificate(pemFilePath string) *Client

SetRootCertificate method helps to add one or more root certificates into resty client

resty.SetRootCertificate("/path/to/root/pemFile.pem")

func (*Client) SetScheme added in v1.7.0

func (c *Client) SetScheme(scheme string) *Client

SetScheme method sets custom scheme in the resty client. It's way to override default.

resty.SetScheme("http")

func (*Client) SetTLSClientConfig

func (c *Client) SetTLSClientConfig(config *tls.Config) *Client

SetTLSClientConfig method sets TLSClientConfig for underling client Transport.

Example:

// One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial
resty.SetTLSClientConfig(&tls.Config{ RootCAs: roots })

// or One can disable security check (https)
resty.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })

Note: This method overwrites existing `TLSClientConfig`.

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration) *Client

SetTimeout method sets timeout for request raised from client.

resty.SetTimeout(time.Duration(1 * time.Minute))

func (*Client) SetTransport added in v1.7.0

func (c *Client) SetTransport(transport http.RoundTripper) *Client

SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` compatible interface implementation in the resty client.

NOTE:

- If transport is not type of `*http.Transport` then you may not be able to take advantage of some of the `resty` client settings.

- It overwrites the resty client transport instance and it's configurations.

transport := &http.Transport{
	// somthing like Proxying to httptest.Server, etc...
	Proxy: func(req *http.Request) (*url.URL, error) {
		return url.Parse(server.URL)
	},
}

resty.SetTransport(transport)

type File added in v1.7.0

type File struct {
	Name      string
	ParamName string
	io.Reader
}

File represent file information for multipart request

func (*File) String added in v1.7.0

func (f *File) String() string

String returns string value of current file details

type Option added in v1.7.0

type Option func(*Options)

Option is to create convenient retry options like wait time, max retries, etc.

func MaxWaitTime added in v1.7.0

func MaxWaitTime(value time.Duration) Option

MaxWaitTime sets the max wait time to sleep between requests

func Retries added in v1.7.0

func Retries(value int) Option

Retries sets the max number of retries

func RetryConditions added in v1.7.0

func RetryConditions(conditions []RetryConditionFunc) Option

RetryConditions sets the conditions that will be checked for retry.

func WaitTime added in v1.7.0

func WaitTime(value time.Duration) Option

WaitTime sets the default wait time to sleep between requests

type Options added in v1.7.0

type Options struct {
	// contains filtered or unexported fields
}

Options to hold go-resty retry values

type RedirectPolicy

type RedirectPolicy interface {
	Apply(req *http.Request, via []*http.Request) error
}

RedirectPolicy to regulate the redirects in the resty client. Objects implementing the RedirectPolicy interface can be registered as

Apply function should return nil to continue the redirect jounery, otherwise return error to stop the redirect.

func DomainCheckRedirectPolicy

func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy

DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client. Redirect is allowed for only mentioned host in the policy.

resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))

func FlexibleRedirectPolicy

func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy

FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client.

resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))

func NoRedirectPolicy

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy is used to disable redirects in the HTTP client

resty.SetRedirectPolicy(NoRedirectPolicy())

type RedirectPolicyFunc

type RedirectPolicyFunc func(*http.Request, []*http.Request) error

The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f.

func (RedirectPolicyFunc) Apply

func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error

Apply calls f(req, via).

type Request

type Request struct {
	URL        string
	Method     string
	Token      string
	QueryParam url.Values
	FormData   url.Values
	Header     http.Header
	Time       time.Time
	Body       interface{}
	Result     interface{}
	Error      interface{}
	RawRequest *http.Request
	SRV        *SRVRecord
	UserInfo   *User
	// contains filtered or unexported fields
}

Request type is used to compose and send individual request from client go-resty is provide option override client level settings such as Auth Token, Basic Auth credentials, Header, Query Param, Form Data, Error object and also you can add more options for that particular request

func NewRequest added in v1.7.0

func NewRequest() *Request

NewRequest is an alias for R(). Creates a new resty request object, it is used form a HTTP/RESTful request such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.

func R

func R() *Request

R creates a new resty request object, it is used form a HTTP/RESTful request such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.

func (*Request) Delete

func (r *Request) Delete(url string) (*Response, error)

Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231.

func (*Request) Execute added in v0.4.1

func (r *Request) Execute(method, url string) (*Response, error)

Execute method performs the HTTP request with given HTTP method and URL for current `Request`.

resp, err := resty.R().Execute(resty.GET, "http://httpbin.org/get")

func (*Request) ExpectContentType added in v1.7.0

func (r *Request) ExpectContentType(contentType string) *Request

ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling when `Content-Type` response header is unavailable.

func (*Request) Get

func (r *Request) Get(url string) (*Response, error)

Get method does GET HTTP request. It's defined in section 4.3.1 of RFC7231.

func (*Request) Head

func (r *Request) Head(url string) (*Response, error)

Head method does HEAD HTTP request. It's defined in section 4.3.2 of RFC7231.

func (*Request) Options

func (r *Request) Options(url string) (*Response, error)

Options method does OPTIONS HTTP request. It's defined in section 4.3.7 of RFC7231.

func (*Request) Patch

func (r *Request) Patch(url string) (*Response, error)

Patch method does PATCH HTTP request. It's defined in section 2 of RFC5789.

func (*Request) Post

func (r *Request) Post(url string) (*Response, error)

Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231.

func (*Request) Put

func (r *Request) Put(url string) (*Response, error)

Put method does PUT HTTP request. It's defined in section 4.3.4 of RFC7231.

func (*Request) SetAuthToken

func (r *Request) SetAuthToken(token string) *Request

SetAuthToken method sets bearer auth token header in the current HTTP request. Header example:

Authorization: Bearer <auth-token-value-comes-here>

Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F

resty.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")

This method overrides the Auth token set by method `resty.SetAuthToken`.

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth method sets the basic authentication header in the current HTTP request. For Header example:

Authorization: Basic <base64-encoded-value>

To set the header for username "go-resty" and password "welcome"

resty.R().SetBasicAuth("go-resty", "welcome")

This method overrides the credentials set by method `resty.SetBasicAuth`.

func (*Request) SetBody

func (r *Request) SetBody(body interface{}) *Request

SetBody method sets the request body for the request. It supports various realtime need easy. We can say its quite handy or powerful. Supported request body data types is `string`, `[]byte`, `struct` and `map`. Body value can be pointer or non-pointer. Automatic marshalling for JSON and XML content type, if it is `struct` or `map`.

Example:

Struct as a body input, based on content type, it will be marshalled.

resty.R().
	SetBody(User{
		Username: "jeeva@myjeeva.com",
		Password: "welcome2resty",
	})

Map as a body input, based on content type, it will be marshalled.

resty.R().
	SetBody(map[string]interface{}{
		"username": "jeeva@myjeeva.com",
		"password": "welcome2resty",
		"address": &Address{
			Address1: "1111 This is my street",
			Address2: "Apt 201",
			City: "My City",
			State: "My State",
			ZipCode: 00000,
		},
	})

String as a body input. Suitable for any need as a string input.

resty.R().
	SetBody(`{
		"username": "jeeva@getrightcare.com",
		"password": "admin"
	}`)

[]byte as a body input. Suitable for raw request such as file upload, serialize & deserialize, etc.

resty.R().
	SetBody([]byte("This is my raw request, sent as-is"))

func (*Request) SetContentLength

func (r *Request) SetContentLength(l bool) *Request

SetContentLength method sets the HTTP header `Content-Length` value for current request. By default go-resty won't set `Content-Length`. Also you have an option to enable for every request. See `resty.SetContentLength`

resty.R().SetContentLength(true)

func (*Request) SetContext added in v1.7.0

func (r *Request) SetContext(ctx context.Context) *Request

SetContext method sets the context.Context for current Request. It allows to interrupt the request execution if ctx.Done() channel is closed. See https://blog.golang.org/context article and the "context" package documentation.

func (*Request) SetDoNotParseResponse added in v1.7.0

func (r *Request) SetDoNotParseResponse(parse bool) *Request

SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, otherwise you might get into connection leaks, no connection reuse.

Please Note: Response middlewares are not applicable, if you use this option. Basically you have taken over the control of response parsing from `Resty`.

func (*Request) SetError

func (r *Request) SetError(err interface{}) *Request

SetError method is to register the request `Error` object for automatic unmarshalling in the RESTful mode if response status code is greater than 399 and content type either JSON or XML.

Note: Error object can be pointer or non-pointer.

resty.R().SetError(&AuthError{})
// OR
resty.R().SetError(AuthError{})

Accessing a error value

response.Error().(*AuthError)

func (*Request) SetFile

func (r *Request) SetFile(param, filePath string) *Request

SetFile method is to set single file field name and its path for multipart upload.

resty.R().
	SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf")

func (*Request) SetFileReader added in v1.7.0

func (r *Request) SetFileReader(param, fileName string, reader io.Reader) *Request

SetFileReader method is to set single file using io.Reader for multipart upload.

resty.R().
	SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)).
	SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes))

func (*Request) SetFiles

func (r *Request) SetFiles(files map[string]string) *Request

SetFiles method is to set multiple file field name and its path for multipart upload.

resty.R().
	SetFiles(map[string]string{
			"my_file1": "/Users/jeeva/Gas Bill - Sep.pdf",
			"my_file2": "/Users/jeeva/Electricity Bill - Sep.pdf",
			"my_file3": "/Users/jeeva/Water Bill - Sep.pdf",
		})

func (*Request) SetFormData

func (r *Request) SetFormData(data map[string]string) *Request

SetFormData method sets Form parameters and their values in the current request. It's applicable only HTTP method `POST` and `PUT` and requests content type would be set as `application/x-www-form-urlencoded`.

resty.R().
	SetFormData(map[string]string{
		"access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
		"user_id": "3455454545",
	})

Also you can override form data value, which was set at client instance level

func (*Request) SetHeader

func (r *Request) SetHeader(header, value string) *Request

SetHeader method is to set a single header field and its value in the current request. Example: To set `Content-Type` and `Accept` as `application/json`.

resty.R().
	SetHeader("Content-Type", "application/json").
	SetHeader("Accept", "application/json")

Also you can override header value, which was set at client instance level.

func (*Request) SetHeaders

func (r *Request) SetHeaders(headers map[string]string) *Request

SetHeaders method sets multiple headers field and its values at one go in the current request. Example: To set `Content-Type` and `Accept` as `application/json`

resty.R().
	SetHeaders(map[string]string{
		"Content-Type": "application/json",
		"Accept": "application/json",
	})

Also you can override header value, which was set at client instance level.

func (*Request) SetMultiValueFormData added in v1.7.0

func (r *Request) SetMultiValueFormData(params url.Values) *Request

SetMultiValueFormData method appends multiple form parameters with multi-value at one go in the current request.

resty.R().
	SetMultiValueFormData(url.Values{
		"search_criteria": []string{"book", "glass", "pencil"},
	})

Also you can override form data value, which was set at client instance level

func (*Request) SetMultiValueQueryParams added in v1.7.0

func (r *Request) SetMultiValueQueryParams(params url.Values) *Request

SetMultiValueQueryParams method appends multiple parameters with multi-value at one go in the current request. It will be formed as query string for the request. Example: `status=pending&status=approved&status=open` in the URL after `?` mark.

resty.R().
	SetMultiValueQueryParams(url.Values{
		"status": []string{"pending", "approved", "open"},
	})

Also you can override query params value, which was set at client instance level

func (*Request) SetMultipartField added in v1.7.0

func (r *Request) SetMultipartField(param, fileName, contentType string, reader io.Reader) *Request

SetMultipartField method is to set custom data using io.Reader for multipart upload.

func (*Request) SetOutput added in v0.4.1

func (r *Request) SetOutput(file string) *Request

SetOutput method sets the output file for current HTTP request. Current HTTP response will be saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used. If is it relative path then output file goes under the output directory, as mentioned in the `Client.SetOutputDirectory`.

resty.R().
	SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip").
	Get("http://bit.ly/1LouEKr")

Note: In this scenario `Response.Body` might be nil.

func (*Request) SetPathParams added in v1.7.0

func (r *Request) SetPathParams(params map[string]string) *Request

SetPathParams method sets multiple URL path key-value pairs at one go in the resty current request instance.

resty.R().SetPathParams(map[string]string{
   "userId": "sample@sample.com",
   "subAccountId": "100002",
})

Result:
   URL - /v1/users/{userId}/{subAccountId}/details
   Composed URL - /v1/users/sample@sample.com/100002/details

It replace the value of the key while composing request URL. Also you can override Path Params value, which was set at client instance level.

func (*Request) SetQueryParam

func (r *Request) SetQueryParam(param, value string) *Request

SetQueryParam method sets single parameter and its value in the current request. It will be formed as query string for the request. Example: `search=kitchen%20papers&size=large` in the URL after `?` mark.

resty.R().
	SetQueryParam("search", "kitchen papers").
	SetQueryParam("size", "large")

Also you can override query params value, which was set at client instance level

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams method sets multiple parameters and its values at one go in the current request. It will be formed as query string for the request. Example: `search=kitchen%20papers&size=large` in the URL after `?` mark.

resty.R().
	SetQueryParams(map[string]string{
		"search": "kitchen papers",
		"size": "large",
	})

Also you can override query params value, which was set at client instance level

func (*Request) SetQueryString added in v0.4.1

func (r *Request) SetQueryString(query string) *Request

SetQueryString method provides ability to use string as an input to set URL query string for the request.

Using String as an input

resty.R().
	SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")

func (*Request) SetResult

func (r *Request) SetResult(res interface{}) *Request

SetResult method is to register the response `Result` object for automatic unmarshalling in the RESTful mode if response status code is between 200 and 299 and content type either JSON or XML.

Note: Result object can be pointer or non-pointer.

resty.R().SetResult(&AuthToken{})
// OR
resty.R().SetResult(AuthToken{})

Accessing a result value

response.Result().(*AuthToken)

func (*Request) SetSRV added in v1.7.0

func (r *Request) SetSRV(srv *SRVRecord) *Request

SetSRV method sets the details to query the service SRV record and execute the request.

resty.R().
	SetSRV(SRVRecord{"web", "testservice.com"}).
	Get("/get")

type Response

type Response struct {
	Request     *Request
	RawResponse *http.Response
	// contains filtered or unexported fields
}

Response is an object represents executed request and its values.

func (*Response) Body

func (r *Response) Body() []byte

Body method returns HTTP response as []byte array for the executed request. Note: `Response.Body` might be nil, if `Request.SetOutput` is used.

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

Cookies method to access all the response cookies

func (*Response) Error

func (r *Response) Error() interface{}

Error method returns the error object if it has one

func (*Response) Header

func (r *Response) Header() http.Header

Header method returns the response headers

func (*Response) IsError added in v1.8.0

func (r *Response) IsError() bool

IsError method returns true if HTTP status code >= 400 otherwise false.

func (*Response) IsSuccess added in v1.8.0

func (r *Response) IsSuccess() bool

IsSuccess method returns true if HTTP status code >= 200 and <= 299 otherwise false.

func (*Response) RawBody added in v1.7.0

func (r *Response) RawBody() io.ReadCloser

RawBody method exposes the HTTP raw response body. Use this method in-conjunction with `SetDoNotParseResponse` option otherwise you get an error as `read err: http: read on closed response body`.

Do not forget to close the body, otherwise you might get into connection leaks, no connection reuse. Basically you have taken over the control of response parsing from `Resty`.

func (*Response) ReceivedAt

func (r *Response) ReceivedAt() time.Time

ReceivedAt method returns when response got recevied from server for the request.

func (*Response) Result

func (r *Response) Result() interface{}

Result method returns the response value as an object if it has one

func (*Response) Size added in v0.4.1

func (r *Response) Size() int64

Size method returns the HTTP response size in bytes. Ya, you can relay on HTTP `Content-Length` header, however it won't be good for chucked transfer/compressed response. Since Resty calculates response size at the client end. You will get actual size of the http response.

func (*Response) Status

func (r *Response) Status() string

Status method returns the HTTP status string for the executed request.

Example: 200 OK

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode method returns the HTTP status code for the executed request.

Example: 200

func (*Response) String

func (r *Response) String() string

String method returns the body of the server response as String.

func (*Response) Time

func (r *Response) Time() time.Duration

Time method returns the time of HTTP response time that from request we sent and received a request. See `response.ReceivedAt` to know when client recevied response and see `response.Request.Time` to know when client sent a request.

type RetryConditionFunc added in v1.7.0

type RetryConditionFunc func(*Response) (bool, error)

RetryConditionFunc type is for retry condition function

type SRVRecord added in v1.7.0

type SRVRecord struct {
	Service string
	Domain  string
}

SRVRecord holds the data to query the SRV record for the following service

type User

type User struct {
	Username, Password string
}

User type is to hold an username and password information

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL