req

package module
v2.0.0-alpha.8 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2022 License: MIT Imports: 49 Imported by: 3

README

req

GoDoc

A golang http request library for humans.

Table of Contents

Features

  • Simple and chainable methods for client and request settings, less code and more efficiency.
  • Global wrapper of both Client and Request for testing purposes, so that you don't even need to create the client or request explicitly, make API testing minimal, and even replace tools like postman, curl with code (see Use Global Methods).
  • There are some common settings between Client level and Request level, you can override Client settings at Request level if you want to (common settings pattern is Request.SetXXX vs Client.SetCommonXXX).
  • Automatically detect charset and decode it to utf-8 by default.
  • Powerful debugging capabilities, including logging, tracing, and even dump the requests and responses' content (see Debug).
  • All settings can be changed dynamically, making it possible to debug in the production environment.
  • Easy to integrate with existing code, just replace the Transport of existing http.Client, then you can dump content as req to debug APIs.

Quick Start

Install

go get github.com/imroc/req/v2@v2.0.0-alpha.8

Import

import "github.com/imroc/req/v2"

Simple GET

// Create and send a request with the global default client, use
// DevMode to see all details, try and suprise :)
req.DevMode()
resp, err := req.Get("https://api.github.com/users/imroc")

// Create and send a request with the custom client
client := req.C().DevMode()
resp, err := client.R().Get("https://api.github.com/users/imroc")

Client Settings

// Create a client with custom client settings using chainable method
client := req.C().SetUserAgent("my-custom-client").SetTimeout(5 * time.Second).DevMode()

// You can also configure the global client using the same chainable method,
// req wraps global method for default client 
req.SetUserAgent("my-custom-client").SetTimeout(5 * time.Second).DevMode()

Request Settings

// Use client to create a request with custom request settings
client := req.C().DevMode()
var result Result
resp, err := client.R().
    SetHeader("Accept", "application/json").
    SetQueryParam("page", "1").
    SetPathParam("userId", "imroc").
    SetResult(&result).
    Get(url)

// You can also create a request using global client using the same chaining method
resp, err := req.R().
    SetHeader("Accept", "application/json").
    SetQueryParam("page", "1").
    SetPathParam("userId", "imroc").
    SetResult(&result).
    Get(url)

// You can even also create a request without calling R(), cuz req
// wraps global method for request, and create a request using
// the default client automatically.
resp, err := req.SetHeader("Accept", "application/json").
    SetQueryParam("page", "1").
    SetPathParam("userId", "imroc").
    SetResult(&result).
    Get(url)

Debug

Dump the content of request and response

// Set EnableDump to true, dump all content to stdout by default,
// including both the header and body of all request and response
client := req.C().EnableDump(true)
client.R().Get("https://api.github.com/users/imroc")

/* Output
:authority: api.github.com
:method: GET
:path: /users/imroc
:scheme: https
user-agent: req/v2 (https://github.com/imroc/req)
accept-encoding: gzip

:status: 200
server: GitHub.com
date: Fri, 21 Jan 2022 09:31:43 GMT
content-type: application/json; charset=utf-8
cache-control: public, max-age=60, s-maxage=60
vary: Accept, Accept-Encoding, Accept, X-Requested-With
etag: W/"fe5acddc5c01a01153ebc4068a1f067dadfa7a7dc9a025f44b37b0a0a50e2c55"
last-modified: Thu, 08 Jul 2021 12:11:23 GMT
x-github-media-type: github.v3; format=json
access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset
access-control-allow-origin: *
strict-transport-security: max-age=31536000; includeSubdomains; preload
x-frame-options: deny
x-content-type-options: nosniff
x-xss-protection: 0
referrer-policy: origin-when-cross-origin, strict-origin-when-cross-origin
content-security-policy: default-src 'none'
content-encoding: gzip
x-ratelimit-limit: 60
x-ratelimit-remaining: 59
x-ratelimit-reset: 1642761103
x-ratelimit-resource: core
x-ratelimit-used: 1
accept-ranges: bytes
content-length: 486
x-github-request-id: AF10:6205:BA107D:D614F2:61EA7D7E

{"login":"imroc","id":7448852,"node_id":"MDQ6VXNlcjc0NDg4NTI=","avatar_url":"https://avatars.githubusercontent.com/u/7448852?v=4","gravatar_id":"","url":"https://api.github.com/users/imroc","html_url":"https://github.com/imroc","followers_url":"https://api.github.com/users/imroc/followers","following_url":"https://api.github.com/users/imroc/following{/other_user}","gists_url":"https://api.github.com/users/imroc/gists{/gist_id}","starred_url":"https://api.github.com/users/imroc/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/imroc/subscriptions","organizations_url":"https://api.github.com/users/imroc/orgs","repos_url":"https://api.github.com/users/imroc/repos","events_url":"https://api.github.com/users/imroc/events{/privacy}","received_events_url":"https://api.github.com/users/imroc/received_events","type":"User","site_admin":false,"name":"roc","company":"Tencent","blog":"https://imroc.cc","location":"China","email":null,"hireable":true,"bio":"I'm roc","twitter_username":"imrocchan","public_repos":128,"public_gists":0,"followers":362,"following":151,"created_at":"2014-04-30T10:50:46Z","updated_at":"2021-07-08T12:11:23Z"}
*/
	
// Dump header content asynchronously and save it to file
client.EnableDumpOnlyHeader(). // Only dump the header of request and response
    EnableDumpAsync(). // Dump asynchronously to improve performance
    EnableDumpToFile("reqdump.log") // Dump to file without printing it out
client.R().Get(url)

// Enable dump with fully customized settings
opt := &req.DumpOptions{
            Output:         os.Stdout,
            RequestHeader:  true,
            ResponseBody:   true,
            RequestBody:    false,
            ResponseHeader: false,
            Async:          false,
        }
client.SetDumpOptions(opt).EnableDump(true)
client.R().Get("https://www.baidu.com/")

// Change settings dynamiclly
opt.ResponseBody = false
client.R().Get("https://www.baidu.com/")

Debug Logging

// Logging is enabled by default, but only output warning and error message to stdout.
// EnableDebug set to true to enable debug level message logging.
client := req.C().EnableDebug(true)
client.R().Get("https://api.github.com/users/imroc")
// Output
// 2022/01/23 14:33:04.755019 DEBUG [req] GET https://api.github.com/users/imroc

// SetLogger with nil to disable all log
client.SetLogger(nil)

// Or customize the logger with your own implementation.
client.SetLogger(logger)

DevMode

If you want to enable all debug features (dump, debug logging and tracing), just call DevMode():

client := req.C().DevMode()
client.R().Get("https://imroc.cc")

Set Path and Query Parameter

Set Path Parameter

Use PathParam to replace variable in the url path:

client := req.C().DevMode()

client.R().
    SetPathParam("owner", "imroc"). // Set a path param, which will replace the vairable in url path
    SetPathParams(map[string]string{ // Set multiple path params at once 
        "repo": "req",
        "path": "README.md",
    }).Get("https://api.github.com/repos/{owner}/{repo}/contents/{path}") // path parameter will replace path variable in the url
/* Output
2022/01/23 14:43:59.114592 DEBUG [req] GET https://api.github.com/repos/imroc/req/contents/README.md
...
*/

// You can also set the common PathParam for every request on client
client.SetPathParam(k1, v1).SetPathParams(pathParams)
	
resp1, err := client.Get(url1)
...

resp2, err := client.Get(url2)
...

Set Query Parameter

client := req.C().DevMode()

client.R().
    SetQueryParam("a", "a"). // Set a query param, which will be encoded as query parameter in url
    SetQueryParams(map[string]string{ // Set multiple query params at once 
        "b": "b",
        "c": "c",
    }).SetQueryString("d=d&e=e"). // Set query params as a raw query string
    Get("https://api.github.com/repos/imroc/req/contents/README.md?x=x")
/* Output
2022/01/23 14:43:59.114592 DEBUG [req] GET https://api.github.com/repos/imroc/req/contents/README.md?x=x&a=a&b=b&c=c&d=d&e=e
...
*/

// You can also set the common QueryParam for every request on client
client.SetQueryParam(k, v).
    SetQueryParams(queryParams).
    SetQueryString(queryString).
	
resp1, err := client.Get(url1)
...
resp2, err := client.Get(url2)
...

Set Header

// Let's dump the header to see what's going on
client := req.C().EnableDumpOnlyHeader() 

// Send a request with multiple headers and cookies
client.R().
    SetHeader("Accept", "application/json"). // Set one header
    SetHeaders(map[string]string{ // Set multiple headers at once 
        "My-Custom-Header": "My Custom Value",
        "User":             "imroc",
    }).Get("https://www.baidu.com/")

/* Output
GET / HTTP/1.1
Host: www.baidu.com
User-Agent: req/v2 (https://github.com/imroc/req)
Accept: application/json
My-Custom-Header: My Custom Value
User: imroc
Accept-Encoding: gzip

...
*/

// You can also set the common header and cookie for every request on client.
client.SetHeader(header).SetHeaders(headers)

resp1, err := client.R().Get(url1)
...
resp2, err := client.R().Get(url2)
...

Set Cookie

// Let's dump the header to see what's going on
client := req.C().EnableDumpOnlyHeader() 

// Send a request with multiple headers and cookies
client.R().
    SetCookie(&http.Cookie{ // Set one cookie
        Name:     "imroc/req",
        Value:    "This is my custome cookie value",
        Path:     "/",
        Domain:   "baidu.com",
        MaxAge:   36000,
        HttpOnly: false,
        Secure:   true,
    }).SetCookies([]*http.Cookie{ // Set multiple cookies at once 
        &http.Cookie{
            Name:     "testcookie1",
            Value:    "testcookie1 value",
            Path:     "/",
            Domain:   "baidu.com",
            MaxAge:   36000,
            HttpOnly: false,
            Secure:   true,
        },
        &http.Cookie{
            Name:     "testcookie2",
            Value:    "testcookie2 value",
            Path:     "/",
            Domain:   "baidu.com",
            MaxAge:   36000,
            HttpOnly: false,
            Secure:   true,
        },
    }).Get("https://www.baidu.com/")

/* Output
GET / HTTP/1.1
Host: www.baidu.com
User-Agent: req/v2 (https://github.com/imroc/req)
Accept: application/json
Cookie: imroc/req="This is my custome cookie value"; testcookie1="testcookie1 value"; testcookie2="testcookie2 value"
Accept-Encoding: gzip

...
*/

// You can also set the common cookie for every request on client.
client.SetCookie(cookie).SetCookies(cookies)

resp1, err := client.R().Get(url1)
...
resp2, err := client.R().Get(url2)

Set Certificates

client := req.R()

// Set root cert and client cert from file path
client.SetRootCertFromFile("/path/to/root/certs/pemFile1.pem", "/path/to/root/certs/pemFile2.pem", "/path/to/root/certs/pemFile3.pem"). // Set root cert from one or more pem files
    SetCertFromFile("/path/to/client/certs/client.pem", "/path/to/client/certs/client.key") // Set client cert and key cert file
	
// You can also set root cert from string
client.SetRootCertFromString("-----BEGIN CERTIFICATE-----XXXXXX-----END CERTIFICATE-----")

// And set client cert with 
cert1, err := tls.LoadX509KeyPair("/path/to/client/certs/client.pem", "/path/to/client/certs/client.key")
if err != nil {
    log.Fatalf("ERROR client certificate: %s", err)
}
// ...

// you can add more certs if you want
client.SetCert(cert1, cert2, cert3) 

Set Basic Auth and Bearer Token

client := req.C()

// Set basic auth for all request
client.SetCommonBasicAuth("imroc", "123456")

// Set bearer token for all request
client.SetCommonBearerToken("MDc0ZTg5YmU4Yzc5MjAzZGJjM2ZiMzkz")

// Set basic auth for a request, will override client's basic auth setting.
client.R().SetBasicAuth("myusername", "mypassword").Get("https://api.example.com/profile")

// Set bearer token for a request, will override client's bearer token setting.
client.R().SetBearerToken("NGU1ZWYwZDJhNmZhZmJhODhmMjQ3ZDc4").Get("https://api.example.com/profile")

Use Global Methods

req wrap methods of both Client and Request with global methods, very convenient when doing api testing, no need to explicitly create clients and requests to minimize the amount of code.

req.SetTimeout(5 * time.Second).
	SetCommonBasicAuth("imroc", "123456").
	SetUserAgent("my api client").
	DevMode()

req.SetQueryParam("page", "2").
	SetHeader("Accept", "application/json").
	Get("https://api.example.com/repos")

License

Req released under MIT license, refer LICENSE file.

Documentation

Index

Constants

View Source
const (
	CONTENT_TYPE_APPLICATION_JSON_UTF8 = "application/json; charset=UTF-8"
	CONTENT_TYPE_APPLICATION_XML_UTF8  = "application/xml; charset=UTF-8"
	CONTENT_TYPE_TEXT_XML_UTF8         = "text/xml; charset=UTF-8"
	CONTENT_TYPE_TEXT_HTML_UTF8        = "text/html; charset=UTF-8"
	CONTENT_TYPE_TEXT_PLAIN_UTF8       = "text/plain; charset=UTF-8"
)
View Source
const DefaultMaxIdleConnsPerHost = 2

DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.

Variables

View Source
var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

ErrBodyReadAfterClose is returned when reading a Request or Response Body after the body has been closed. This typically happens when the body is read after an HTTP Handler calls WriteHeader or Write on its ResponseWriter.

View Source
var ErrLineTooLong = internal.ErrLineTooLong

ErrLineTooLong is returned when reading request or response bodies with malformed chunked encoding.

View Source
var NoBody = noBody{}

NoBody is an io.ReadCloser with no bytes. Read always returns EOF and Close always returns nil. It can be used in an outgoing client request to explicitly signal that a request has zero bytes. An alternative, however, is to simply set Request.Body to nil.

Functions

func CanonicalMIMEHeaderKey

func CanonicalMIMEHeaderKey(s string) string

CanonicalMIMEHeaderKey returns the canonical format of the MIME header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". MIME header keys are assumed to be ASCII only. If s contains a space or invalid header field bytes, it is returned without modifications.

func ProxyFromEnvironment

func ProxyFromEnvironment(req *http.Request) (*url.URL, error)

ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https requests.

The environment values may be either a complete URL or a "host[:port]", in which case the "http" scheme is assumed. The schemes "http", "https", and "socks5" are supported. An error is returned if the value is a different form.

A nil URL and nil error are returned if no proxy is defined in the environment, or a proxy should not be used for the given request, as defined by NO_PROXY.

As a special case, if req.URL.Host is "localhost" (with or without a port number), then a nil URL and nil error will be returned.

func ProxyURL

func ProxyURL(fixedURL *url.URL) func(*http.Request) (*url.URL, error)

ProxyURL returns a proxy function (for use in a Transport) that always returns the same URL.

func SetDefaultClient

func SetDefaultClient(c *Client)

SetDefaultClient override the global default Client.

Types

type Client

type Client struct {
	HostURL       string
	PathParams    map[string]string
	QueryParams   urlpkg.Values
	Headers       http.Header
	Cookies       []*http.Cookie
	JSONMarshal   func(v interface{}) ([]byte, error)
	JSONUnmarshal func(data []byte, v interface{}) error
	XMLMarshal    func(v interface{}) ([]byte, error)
	XMLUnmarshal  func(data []byte, v interface{}) error
	Debug         bool
	// contains filtered or unexported fields
}

Client is the req's http client.

func C

func C() *Client

C create a new client.

func DefaultClient

func DefaultClient() *Client

DefaultClient returns the global default Client.

func DevMode

func DevMode() *Client

func DisableAutoDecode

func DisableAutoDecode(disable bool) *Client

func DisableAutoReadResponse

func DisableAutoReadResponse(disable bool) *Client

func DisableCompression

func DisableCompression(disable bool) *Client

func DisableKeepAlives

func DisableKeepAlives(disable bool) *Client

func EnableAutoDecodeAllType

func EnableAutoDecodeAllType() *Client

func EnableDebug

func EnableDebug(enable bool) *Client

func EnableDump

func EnableDump(enable bool) *Client

func EnableDumpAll

func EnableDumpAll() *Client

func EnableDumpAsync

func EnableDumpAsync() *Client

func EnableDumpOnlyBody

func EnableDumpOnlyBody() *Client

func EnableDumpOnlyHeader

func EnableDumpOnlyHeader() *Client

func EnableDumpOnlyRequest

func EnableDumpOnlyRequest() *Client

func EnableDumpOnlyResponse

func EnableDumpOnlyResponse() *Client

func EnableDumpTo

func EnableDumpTo(output io.Writer) *Client

func EnableDumpToFile

func EnableDumpToFile(filename string) *Client

func NewClient

func NewClient() *Client

NewClient is the alias of C

func OnAfterResponse

func OnAfterResponse(m ResponseMiddleware) *Client

func OnBeforeRequest

func OnBeforeRequest(m RequestMiddleware) *Client

func SetCert

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

func SetCertFromFile

func SetCertFromFile(certFile, keyFile string) *Client

func SetCommonBasicAuth

func SetCommonBasicAuth(username, password string) *Client

func SetCommonBearerAuthToken

func SetCommonBearerAuthToken(token string) *Client

func SetCommonCookie

func SetCommonCookie(hc *http.Cookie) *Client

func SetCommonCookies

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

func SetCommonHeader

func SetCommonHeader(key, value string) *Client

func SetCommonHeaders

func SetCommonHeaders(hdrs map[string]string) *Client

func SetCommonQueryParam

func SetCommonQueryParam(key, value string) *Client

func SetCommonQueryParams

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

func SetCommonQueryString

func SetCommonQueryString(query string) *Client

func SetDumpOptions

func SetDumpOptions(opt *DumpOptions) *Client

func SetLogger

func SetLogger(log Logger) *Client

func SetOutputDirectory

func SetOutputDirectory(dir string) *Client

func SetProxy

func SetProxy(proxy func(*http.Request) (*urlpkg.URL, error)) *Client

func SetProxyURL

func SetProxyURL(proxyUrl string) *Client

func SetRedirectPolicy

func SetRedirectPolicy(policies ...RedirectPolicy) *Client

func SetResponseOptions

func SetResponseOptions(opt *ResponseOptions) *Client

func SetRootCertFromFile

func SetRootCertFromFile(pemFiles ...string) *Client

func SetRootCertFromString

func SetRootCertFromString(pemContent string) *Client

func SetScheme

func SetScheme(scheme string) *Client

func SetTLSClientConfig

func SetTLSClientConfig(conf *tls.Config) *Client

func SetTimeout

func SetTimeout(d time.Duration) *Client

func SetUserAgent

func SetUserAgent(userAgent string) *Client

func (*Client) Clone

func (c *Client) Clone() *Client

Clone copy and returns the Client

func (*Client) DevMode

func (c *Client) DevMode() *Client

DevMode enables dump for requests and responses, and set user agent to pretend to be a web browser, Avoid returning abnormal data from some sites.

func (*Client) DisableAutoDecode

func (c *Client) DisableAutoDecode(disable bool) *Client

DisableAutoDecode disable auto detect charset and decode to utf-8

func (*Client) DisableAutoReadResponse

func (c *Client) DisableAutoReadResponse(disable bool) *Client

func (*Client) DisableCompression

func (c *Client) DisableCompression(disable bool) *Client

func (*Client) DisableKeepAlives

func (c *Client) DisableKeepAlives(disable bool) *Client

func (*Client) EnableAutoDecodeAllType

func (c *Client) EnableAutoDecodeAllType() *Client

EnableAutoDecodeAllType indicates that try autodetect and decode all content type.

func (*Client) EnableDebug

func (c *Client) EnableDebug(enable bool) *Client

func (*Client) EnableDump

func (c *Client) EnableDump(enable bool) *Client

EnableDump enables dump requests and responses, allowing you to clearly see the content of all requests and responses,which is very convenient for debugging APIs.

func (*Client) EnableDumpAll

func (c *Client) EnableDumpAll() *Client

EnableDumpAll indicates that should dump both requests and responses' head and body.

func (*Client) EnableDumpAsync

func (c *Client) EnableDumpAsync() *Client

EnableDumpAsync indicates that the dump should be done asynchronously, can be used for debugging in production environment without affecting performance.

func (*Client) EnableDumpOnlyBody

func (c *Client) EnableDumpOnlyBody() *Client

EnableDumpOnlyBody indicates that should dump the body of requests and responses.

func (*Client) EnableDumpOnlyHeader

func (c *Client) EnableDumpOnlyHeader() *Client

EnableDumpOnlyHeader indicates that should dump the head of requests and responses.

func (*Client) EnableDumpOnlyRequest

func (c *Client) EnableDumpOnlyRequest() *Client

EnableDumpOnlyRequest indicates that should dump the requests' head and response.

func (*Client) EnableDumpOnlyResponse

func (c *Client) EnableDumpOnlyResponse() *Client

EnableDumpOnlyResponse indicates that should dump the responses' head and response.

func (*Client) EnableDumpTo

func (c *Client) EnableDumpTo(output io.Writer) *Client

EnableDumpTo indicates that the content should dump to the specified destination.

func (*Client) EnableDumpToFile

func (c *Client) EnableDumpToFile(filename string) *Client

EnableDumpToFile indicates that the content should dump to the specified filename.

func (*Client) GetDumpOptions

func (c *Client) GetDumpOptions() *DumpOptions

func (*Client) GetResponseOptions

func (c *Client) GetResponseOptions() *ResponseOptions

func (*Client) NewRequest

func (c *Client) NewRequest() *Request

NewRequest is the alias of R()

func (*Client) OnAfterResponse

func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client

func (*Client) OnBeforeRequest

func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client

func (*Client) R

func (c *Client) R() *Request

R create a new request.

func (*Client) SetCert

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

SetCert helps to set client certificates

func (*Client) SetCertFromFile

func (c *Client) SetCertFromFile(certFile, keyFile string) *Client

SetCertFromFile helps to set client certificates from cert and key file

func (*Client) SetCommonBasicAuth

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

func (*Client) SetCommonBearerAuthToken

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

func (*Client) SetCommonCookie

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

func (*Client) SetCommonCookies

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

func (*Client) SetCommonHeader

func (c *Client) SetCommonHeader(key, value string) *Client

SetCommonHeader set the common header for all requests.

func (*Client) SetCommonHeaders

func (c *Client) SetCommonHeaders(hdrs map[string]string) *Client

func (*Client) SetCommonQueryParam

func (c *Client) SetCommonQueryParam(key, value string) *Client

func (*Client) SetCommonQueryParams

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

func (*Client) SetCommonQueryString

func (c *Client) SetCommonQueryString(query string) *Client

func (*Client) SetDumpOptions

func (c *Client) SetDumpOptions(opt *DumpOptions) *Client

SetDumpOptions configures the underlying Transport's DumpOptions

func (*Client) SetLogger

func (c *Client) SetLogger(log Logger) *Client

SetLogger set the logger for req, set to nil to disable logger.

func (*Client) SetOutputDirectory

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

func (*Client) SetProxy

func (c *Client) SetProxy(proxy func(*http.Request) (*urlpkg.URL, error)) *Client

SetProxy set the proxy function.

func (*Client) SetProxyURL

func (c *Client) SetProxyURL(proxyUrl string) *Client

func (*Client) SetRedirectPolicy

func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client

SetRedirectPolicy helps to set the RedirectPolicy

func (*Client) SetResponseOptions

func (c *Client) SetResponseOptions(opt *ResponseOptions) *Client

SetResponseOptions set the ResponseOptions for the underlying Transport.

func (*Client) SetRootCertFromFile

func (c *Client) SetRootCertFromFile(pemFiles ...string) *Client

SetRootCertFromFile helps to set root cert from files

func (*Client) SetRootCertFromString

func (c *Client) SetRootCertFromString(pemContent string) *Client

SetRootCertFromString helps to set root CA cert from string

func (*Client) SetScheme

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

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

client.SetScheme("http")

func (*Client) SetTLSClientConfig

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

func (*Client) SetTimeout

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

SetTimeout set the timeout for all requests.

func (*Client) SetUserAgent

func (c *Client) SetUserAgent(userAgent string) *Client

SetUserAgent set the "User-Agent" header for all requests.

type DumpOptions

type DumpOptions struct {
	Output         io.Writer
	RequestHeader  bool
	RequestBody    bool
	ResponseHeader bool
	ResponseBody   bool
	Async          bool
}

DumpOptions controls the dump behavior.

func GetDumpOptions

func GetDumpOptions() *DumpOptions

func (*DumpOptions) Clone

func (do *DumpOptions) Clone() *DumpOptions

type Logger

type Logger interface {
	Errorf(format string, v ...interface{})
	Warnf(format string, v ...interface{})
	Debugf(format string, v ...interface{})
}

Logger interface is to abstract the logging from Resty. Gives control to the Resty users, choice of the logger.

func NewLogger

func NewLogger(output io.Writer, prefix string, flag int) Logger

NewLogger create a Logger wraps the *log.Logger

type RedirectPolicy

type RedirectPolicy func(req *http.Request, via []*http.Request) error

func AllowedDomainRedirectPolicy

func AllowedDomainRedirectPolicy(hosts ...string) RedirectPolicy

AllowedDomainRedirectPolicy allows redirect only if the redirected domain match one of the domain that specified.

func AllowedHostRedirectPolicy

func AllowedHostRedirectPolicy(hosts ...string) RedirectPolicy

AllowedHostRedirectPolicy allows redirect only if the redirected host match one of the host that specified.

func MaxRedirectPolicy

func MaxRedirectPolicy(noOfRedirect int) RedirectPolicy

MaxRedirectPolicy specifies the max number of redirect

func NoRedirectPolicy

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy disable redirect behaviour

func SameDomainRedirectPolicy

func SameDomainRedirectPolicy() RedirectPolicy

func SameHostRedirectPolicy

func SameHostRedirectPolicy() RedirectPolicy

SameHostRedirectPolicy allows redirect only if the redirected host is the same as original host, e.g. redirect to "www.imroc.cc" from "imroc.cc" is not the allowed.

type Request

type Request struct {
	URL         string
	PathParams  map[string]string
	QueryParams urlpkg.Values
	Headers     http.Header
	Cookies     []*http.Cookie
	Result      interface{}
	Error       interface{}

	RawRequest *http.Request
	// contains filtered or unexported fields
}

Request is the http request

func NewRequest

func NewRequest() *Request

func R

func R() *Request

func SetBasicAuth

func SetBasicAuth(username, password string) *Request

func SetBearerAuthToken

func SetBearerAuthToken(token string) *Request

func SetBody

func SetBody(body interface{}) *Request

func SetBodyBytes

func SetBodyBytes(body []byte) *Request

func SetBodyJsonBytes

func SetBodyJsonBytes(body []byte) *Request

func SetBodyJsonMarshal

func SetBodyJsonMarshal(v interface{}) *Request

func SetBodyJsonString

func SetBodyJsonString(body string) *Request

func SetBodyString

func SetBodyString(body string) *Request

func SetContentType

func SetContentType(contentType string) *Request

func SetCookie

func SetCookie(hc *http.Cookie) *Request

func SetCookies

func SetCookies(rs []*http.Cookie) *Request

func SetError

func SetError(error interface{}) *Request

func SetHeader

func SetHeader(key, value string) *Request

func SetHeaders

func SetHeaders(hdrs map[string]string) *Request

func SetOutput

func SetOutput(output io.WriteCloser) *Request

func SetOutputFile

func SetOutputFile(file string) *Request

func SetPathParam

func SetPathParam(key, value string) *Request

func SetPathParams

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

func SetQueryParam

func SetQueryParam(key, value string) *Request

func SetQueryParams

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

func SetQueryString

func SetQueryString(query string) *Request

func SetResult

func SetResult(result interface{}) *Request

func (*Request) Delete

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

Delete Send the request with DELETE method and specified url.

func (*Request) Get

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

Get Send the request with GET method and specified url.

func (*Request) Head

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

Head Send the request with HEAD method and specified url.

func (*Request) MustDelete

func (r *Request) MustDelete(url string) *Response

MustDelete like Delete, panic if error happens.

func (*Request) MustGet

func (r *Request) MustGet(url string) *Response

MustGet like Get, panic if error happens.

func (*Request) MustHead

func (r *Request) MustHead(url string) *Response

MustHead like Head, panic if error happens.

func (*Request) MustOptions

func (r *Request) MustOptions(url string) *Response

MustOptions like Options, panic if error happens.

func (*Request) MustPatch

func (r *Request) MustPatch(url string) *Response

MustPatch like Patch, panic if error happens.

func (*Request) MustPost

func (r *Request) MustPost(url string) *Response

MustPost like Post, panic if error happens.

func (*Request) MustPut

func (r *Request) MustPut(url string) *Response

MustPut like Put, panic if error happens.

func (*Request) Options

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

Options Send the request with OPTIONS method and specified url.

func (*Request) Patch

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

Patch Send the request with PATCH method and specified url.

func (*Request) Post

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

Post Send the request with POST method and specified url.

func (*Request) Put

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

Put Send the request with Put method and specified url.

func (*Request) Send

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

func (*Request) SetBasicAuth

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

func (*Request) SetBearerAuthToken

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

func (*Request) SetBody

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

SetBody set the request body.

func (*Request) SetBodyBytes

func (r *Request) SetBodyBytes(body []byte) *Request

SetBodyBytes set the request body as []byte.

func (*Request) SetBodyJsonBytes

func (r *Request) SetBodyJsonBytes(body []byte) *Request

SetBodyJsonBytes set the request body as []byte and set Content-Type header as "application/json; charset=UTF-8"

func (*Request) SetBodyJsonMarshal

func (r *Request) SetBodyJsonMarshal(v interface{}) *Request

SetBodyJsonMarshal set the request body that marshaled from object, and set Content-Type header as "application/json; charset=UTF-8"

func (*Request) SetBodyJsonString

func (r *Request) SetBodyJsonString(body string) *Request

SetBodyJsonString set the request body as string and set Content-Type header as "application/json; charset=UTF-8"

func (*Request) SetBodyString

func (r *Request) SetBodyString(body string) *Request

SetBodyString set the request body as string.

func (*Request) SetContentType

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

func (*Request) SetCookie

func (r *Request) SetCookie(hc *http.Cookie) *Request

func (*Request) SetCookies

func (r *Request) SetCookies(rs []*http.Cookie) *Request

func (*Request) SetError

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

func (*Request) SetHeader

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

SetHeader set the common header for all requests.

func (*Request) SetHeaders

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

func (*Request) SetOutput

func (r *Request) SetOutput(output io.WriteCloser) *Request

func (*Request) SetOutputFile

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

func (*Request) SetPathParam

func (r *Request) SetPathParam(key, value string) *Request

func (*Request) SetPathParams

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

func (*Request) SetQueryParam

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

func (*Request) SetQueryParams

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

func (*Request) SetQueryString

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

func (*Request) SetResult

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

type RequestMiddleware

type RequestMiddleware func(*Client, *Request) error

RequestMiddleware type is for request middleware, called before a request is sent

type Response

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

Response is the http response.

func Delete

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

func Get

func Get(url string) (*Response, error)
func Head(url string) (*Response, error)

func MustDelete

func MustDelete(url string) *Response

func MustGet

func MustGet(url string) *Response

func MustHead

func MustHead(url string) *Response

func MustOptions

func MustOptions(url string) *Response

func MustPatch

func MustPatch(url string) *Response

func MustPost

func MustPost(url string) *Response

func MustPut

func MustPut(url string) *Response

func Options

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

func Patch

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

func Post

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

func Put

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

func (*Response) Bytes

func (r *Response) Bytes() ([]byte, error)

func (*Response) Error

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

Error method returns the error object if it has one

func (*Response) GetContentType

func (r *Response) GetContentType() string

func (*Response) IsError

func (r *Response) IsError() bool

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

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

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

func (*Response) MustBytes

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

func (*Response) MustString

func (r *Response) MustString() string

func (*Response) MustUnmarshal

func (r *Response) MustUnmarshal(v interface{})

func (*Response) MustUnmarshalJson

func (r *Response) MustUnmarshalJson(v interface{})

func (*Response) MustUnmarshalXml

func (r *Response) MustUnmarshalXml(v interface{})

func (*Response) Result

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

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

func (*Response) String

func (r *Response) String() (string, error)

func (*Response) Unmarshal

func (r *Response) Unmarshal(v interface{}) error

func (*Response) UnmarshalJson

func (r *Response) UnmarshalJson(v interface{}) error

func (*Response) UnmarshalXml

func (r *Response) UnmarshalXml(v interface{}) error

type ResponseMiddleware

type ResponseMiddleware func(*Client, *Response) error

ResponseMiddleware type is for response middleware, called after a response has been received

type ResponseOptions

type ResponseOptions struct {
	// DisableAutoDecode, if true, prevents auto detect response
	// body's charset and decode it to utf-8
	DisableAutoDecode bool

	// AutoDecodeContentType specifies an optional function for determine
	// whether the response body should been auto decode to utf-8.
	// Only valid when DisableAutoDecode is true.
	AutoDecodeContentType func(contentType string) bool
}

ResponseOptions determines that how should the response been processed.

func GetResponseOptions

func GetResponseOptions() *ResponseOptions

type Transport

type Transport struct {

	// Proxy specifies a function to return a proxy for a given
	// Request. If the function returns a non-nil error, the
	// request is aborted with the provided error.
	//
	// The proxy type is determined by the URL scheme. "http",
	// "https", and "socks5" are supported. If the scheme is empty,
	// "http" is assumed.
	//
	// If Proxy is nil or returns a nil *URL, no proxy is used.
	Proxy func(*http.Request) (*url.URL, error)

	// DialContext specifies the dial function for creating unencrypted TCP connections.
	// If DialContext is nil (and the deprecated Dial below is also nil),
	// then the transport dials using package net.
	//
	// DialContext runs concurrently with calls to RoundTrip.
	// A RoundTrip call that initiates a dial may end up using
	// a connection dialed previously when the earlier connection
	// becomes idle before the later DialContext completes.
	DialContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// Dial specifies the dial function for creating unencrypted TCP connections.
	//
	// Dial runs concurrently with calls to RoundTrip.
	// A RoundTrip call that initiates a dial may end up using
	// a connection dialed previously when the earlier connection
	// becomes idle before the later Dial completes.
	//
	// Deprecated: Use DialContext instead, which allows the transport
	// to cancel dials as soon as they are no longer needed.
	// If both are set, DialContext takes priority.
	Dial func(network, addr string) (net.Conn, error)

	// DialTLSContext specifies an optional dial function for creating
	// TLS connections for non-proxied HTTPS requests.
	//
	// If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
	// DialContext and TLSClientConfig are used.
	//
	// If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
	// requests and the TLSClientConfig and TLSHandshakeTimeout
	// are ignored. The returned net.Conn is assumed to already be
	// past the TLS handshake.
	DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// DialTLS specifies an optional dial function for creating
	// TLS connections for non-proxied HTTPS requests.
	//
	// Deprecated: Use DialTLSContext instead, which allows the transport
	// to cancel dials as soon as they are no longer needed.
	// If both are set, DialTLSContext takes priority.
	DialTLS func(network, addr string) (net.Conn, error)

	// TLSClientConfig specifies the TLS configuration to use with
	// tls.Client.
	// If nil, the default configuration is used.
	// If non-nil, HTTP/2 support may not be enabled by default.
	TLSClientConfig *tls.Config

	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout time.Duration

	// DisableKeepAlives, if true, disables HTTP keep-alives and
	// will only use the connection to the server for a single
	// HTTP request.
	//
	// This is unrelated to the similarly named TCP keep-alives.
	DisableKeepAlives bool

	// DisableCompression, if true, prevents the Transport from
	// requesting compression with an "Accept-Encoding: gzip"
	// request header when the Request contains no existing
	// Accept-Encoding value. If the Transport requests gzip on
	// its own and gets a gzipped response, it's transparently
	// decoded in the Response.Body. However, if the user
	// explicitly requested gzip it is not automatically
	// uncompressed.
	DisableCompression bool

	// MaxIdleConns controls the maximum number of idle (keep-alive)
	// connections across all hosts. Zero means no limit.
	MaxIdleConns int

	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host. If zero,
	// DefaultMaxIdleConnsPerHost is used.
	MaxIdleConnsPerHost int

	// MaxConnsPerHost optionally limits the total number of
	// connections per host, including connections in the dialing,
	// active, and idle states. On limit violation, dials will block.
	//
	// Zero means no limit.
	MaxConnsPerHost int

	// IdleConnTimeout is the maximum amount of time an idle
	// (keep-alive) connection will remain idle before closing
	// itself.
	// Zero means no limit.
	IdleConnTimeout time.Duration

	// ResponseHeaderTimeout, if non-zero, specifies the amount of
	// time to wait for a server's response headers after fully
	// writing the request (including its body, if any). This
	// time does not include the time to read the response body.
	ResponseHeaderTimeout time.Duration

	// ExpectContinueTimeout, if non-zero, specifies the amount of
	// time to wait for a server's first response headers after fully
	// writing the request headers if the request has an
	// "Expect: 100-continue" header. Zero means no timeout and
	// causes the body to be sent immediately, without
	// waiting for the server to approve.
	// This time does not include the time to send the request header.
	ExpectContinueTimeout time.Duration

	// TLSNextProto specifies how the Transport switches to an
	// alternate protocol (such as HTTP/2) after a TLS ALPN
	// protocol negotiation. If Transport dials an TLS connection
	// with a non-empty protocol name and TLSNextProto contains a
	// map entry for that key (such as "h2"), then the func is
	// called with the request's authority (such as "example.com"
	// or "example.com:1234") and the TLS connection. The function
	// must return a http.RoundTripper that then handles the request.
	// If TLSNextProto is not nil, HTTP/2 support is not enabled
	// automatically.
	TLSNextProto map[string]func(authority string, c *tls.Conn) http.RoundTripper

	// ProxyConnectHeader optionally specifies headers to send to
	// proxies during CONNECT requests.
	// To set the header dynamically, see GetProxyConnectHeader.
	ProxyConnectHeader http.Header

	// GetProxyConnectHeader optionally specifies a func to return
	// headers to send to proxyURL during a CONNECT request to the
	// ip:port target.
	// If it returns an error, the Transport's RoundTrip fails with
	// that error. It can return (nil, nil) to not add headers.
	// If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
	// ignored.
	GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (http.Header, error)

	// MaxResponseHeaderBytes specifies a limit on how many
	// response bytes are allowed in the server's response
	// header.
	//
	// Zero means to use a default limit.
	MaxResponseHeaderBytes int64

	// WriteBufferSize specifies the size of the write buffer used
	// when writing to the transport.
	// If zero, a default (currently 4KB) is used.
	WriteBufferSize int

	// ReadBufferSize specifies the size of the read buffer used
	// when reading from the transport.
	// If zero, a default (currently 4KB) is used.
	ReadBufferSize int

	// ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
	// Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
	// By default, use of any those fields conservatively disables HTTP/2.
	// To use a custom dialer or TLS config and still attempt HTTP/2
	// upgrades, set this to true.
	ForceAttemptHTTP2 bool

	*ResponseOptions
	// contains filtered or unexported fields
}

Transport is an implementation of http.RoundTripper that supports HTTP, HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).

By default, Transport caches connections for future re-use. This may leave many open connections when accessing many hosts. This behavior can be managed using Transport's CloseIdleConnections method and the MaxIdleConnsPerHost and DisableKeepAlives fields.

Transports should be reused instead of created as needed. Transports are safe for concurrent use by multiple goroutines.

A Transport is a low-level primitive for making HTTP and HTTPS requests. For high-level functionality, such as cookies and redirects, see Client.

Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 for HTTPS URLs, depending on whether the server supports HTTP/2, and how the Transport is configured. The DefaultTransport supports HTTP/2. To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2 and call ConfigureTransport. See the package docs for more about HTTP/2.

Responses with status codes in the 1xx range are either handled automatically (100 expect-continue) or ignored. The one exception is HTTP status code 101 (Switching Protocols), which is considered a terminal status and returned by RoundTrip. To see the ignored 1xx responses, use the httptrace trace package's ClientTrace.Got1xxResponse.

Transport only retries a request upon encountering a network error if the request is idempotent and either has no body or has its Request.GetBody defined. HTTP requests are considered idempotent if they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their Header map contains an "Idempotency-Key" or "X-Idempotency-Key" entry. If the idempotency key value is a zero-length slice, the request is treated as idempotent but the header is not sent on the wire.

func (*Transport) CancelRequest deprecated

func (t *Transport) CancelRequest(req *http.Request)

CancelRequest cancels an in-flight request by closing its connection. CancelRequest should only be called after RoundTrip has returned.

Deprecated: Use Request.WithContext to create a request with a cancelable context instead. CancelRequest cannot cancel HTTP/2 requests.

func (*Transport) Clone

func (t *Transport) Clone() *Transport

Clone returns a deep copy of t's exported fields.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

func (*Transport) DisableDump

func (t *Transport) DisableDump()

func (*Transport) EnableDump

func (t *Transport) EnableDump(opt *DumpOptions)

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(scheme string, rt http.RoundTripper)

RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will handle the RoundTrip itself for that one request, as if the protocol were not registered.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error)

RoundTrip implements the RoundTripper interface.

For higher-level HTTP client support (such as handling of cookies and redirects), see Get, Post, and the Client type.

Like the RoundTripper interface, the error types returned by RoundTrip are unspecified.

Directories

Path Synopsis
Package internal contains HTTP internals shared by net/http and net/http/httputil.
Package internal contains HTTP internals shared by net/http and net/http/httputil.
godebug
Package godebug parses the GODEBUG environment variable.
Package godebug parses the GODEBUG environment variable.

Jump to

Keyboard shortcuts

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