MCPcopy Index your code
hub / github.com/go-resty/resty

github.com/go-resty/resty @v2.17.2 sqlite

repository ↗ · DeepWiki ↗ · release v2.17.2 ↗
594 symbols 4,654 edges 25 files 231 documented · 39% 32 cross-repo links
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 Mentioned in Awesome Go

News

  • v2.17.2 released and tagged on Feb 14, 2026.
  • v2.0.0 released and tagged on Jul 16, 2019.
  • v1.12.0 released and tagged on Feb 27, 2019.
  • v1.0 released and tagged on Sep 25, 2017. - 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 since first release. 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
    • Native *http.Request instance may be accessed during middleware and request execution via Request.RawRequest
    • Request Body can be read multiple times via Request.RawRequest.GetBody()
  • 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
  • Authorization option of BasicAuth and Bearer token
  • Set request ContentLength value for all request or particular request
  • 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 middleware
    • Create Multiple clients if you want to resty.New()
    • Supports http.RoundTripper implementation, see SetTransport
    • goroutine concurrent safe
    • Resty Client trace, see Client.EnableTrace and Request.EnableTrace
    • Since v2.4.0, trace info contains a RequestAttempt value, and the Request object contains an Attempt attribute
    • Supports on-demand CURL command generation, see Client.EnableGenerateCurlOnDebug, Request.EnableGenerateCurlOnDebug. It requires debug mode to be enabled.
    • 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, also HTTP/3 can be used with Resty, see this comment
  • Bazel support
  • Easily mock Resty for testing, for e.g.
  • Well tested client library

Included Batteries

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

Supported Go Versions

Recommended to use go1.23 and above.

Initially Resty started supporting go modules since v1.10.0 release.

Starting Resty v2 and higher versions, it fully embraces go modules package release. It requires a Go version capable of understanding /vN suffixed imports:

  • 1.9.7+
  • 1.10.3+
  • 1.11+

It might be beneficial for your project :smile:

Resty author also published following projects for Go Community.

  • go-model - Robust & Easy to use model mapper and utility methods for Go struct.

Installation

# Go Modules
require github.com/go-resty/resty/v2 v2.16.5

Usage

The following samples will assist you to become as comfortable as possible with resty library.

// Import resty into your code and refer it as `resty`.
import "github.com/go-resty/resty/v2"

Simple GET

// Create a Resty Client
client := resty.New()

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())

/* Output
Response Info:
  Error      : <nil>
  Status Code: 200
  Status     : 200 OK
  Proto      : HTTP/2.0
  Time       : 457.034718ms
  Received At: 2020-09-14 15:35:29.784681 -0700 PDT m=+0.458137045
  Body       :
  {
    "args": {},
    "headers": {
      "Accept-Encoding": "gzip",
      "Host": "httpbin.org",
      "User-Agent": "go-resty/2.4.0 (https://github.com/go-resty/resty)",
      "X-Amzn-Trace-Id": "Root=1-5f5ff031-000ff6292204aa6898e4de49"
    },
    "origin": "0.0.0.0",
    "url": "https://httpbin.org/get"
  }

Request Trace Info:
  DNSLookup     : 4.074657ms
  ConnTime      : 381.709936ms
  TCPConnTime   : 77.428048ms
  TLSHandshake  : 299.623597ms
  ServerTime    : 75.414703ms
  ResponseTime  : 79.337µs
  TotalTime     : 457.034718ms
  IsConnReused  : false
  IsConnWasIdle : false
  ConnIdleTime  : 0s
  RequestAttempt: 1
  RemoteAddr    : 3.221.81.55:443
*/

Enhanced GET

// Create a Resty Client
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")


// Sample of using 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")


// If necessary, you can force response content type to tell Resty to parse a JSON response into your struct
resp, err := client.R().
      SetResult(result).
      ForceContentType("application/json").
      Get("v2/alpine/manifests/latest")

Various POST method combinations

```go // Create a Resty Client client := resty.New()

// POST JSON string // No need to set content type, if you have client level setting resp, 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 setting resp, 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 one resp, 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 one resp, 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 Dropbox fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf")

// See we are not setting content-type header, since go-resty automatically detects Content-Type for you resp, err := client.R(). SetBody(fileBytes). SetContentLength(true). // Dropbox expects this value SetAuthToken(""). 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

Extension points exported contracts — how you extend this code

Logger (Interface)
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ Logger interface _______________________________ [1 …
util.go
RedirectPolicy (Interface)
RedirectPolicy to regulate the redirects in the Resty client. Objects implementing the [RedirectPolicy] interface can be
redirect.go
RequestMiddleware (FuncType)
RequestMiddleware type is for request middleware, called before a request is sent
client.go
Option (FuncType)
Option is to create convenient retry options like wait time, max retries, etc.
retry.go
RateLimiter (Interface)
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ Rate Limiter interface _________________________
util.go
RedirectPolicyFunc (FuncType)
The [RedirectPolicyFunc] type is an adapter to allow the use of ordinary functions as [RedirectPolicy]. If `f` is a func
redirect.go
ResponseMiddleware (FuncType)
ResponseMiddleware type is for response middleware, called after a response has been received
client.go
RetryConditionFunc (FuncType)
RetryConditionFunc type is for the retry condition function input: non-nil Response OR request execution error
retry.go

Core symbols most depended-on inside this repo

R
called by 188
client.go
Get
called by 179
request.go
StatusCode
called by 123
response.go
SetBody
called by 93
request.go
String
called by 93
client.go
Errorf
called by 80
util.go
Post
called by 68
request.go
Error
called by 58
util.go

Shape

Function 342
Method 198
Struct 39
FuncType 12
Interface 3

Languages

Go100%

Modules by API surface

request_test.go116 symbols
client.go101 symbols
request.go63 symbols
client_test.go53 symbols
util.go52 symbols
resty_test.go33 symbols
retry_test.go31 symbols
middleware_test.go20 symbols
response.go19 symbols
retry.go18 symbols
example_test.go16 symbols
middleware.go15 symbols

Dependencies from manifests, versioned

golang.org/x/netv0.43.0 · 1×
golang.org/x/timev0.12.0 · 1×

For agents

$ claude mcp add resty \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact