sreq

package module
v0.9.11 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2020 License: MIT Imports: 36 Imported by: 15

README

sreq

sreq is a simple, user-friendly and concurrent safe HTTP request library for Go, inspired by Python requests .

Build codecov Go Report Card GoDoc License

Notes

  • sreq now is under a beta state, use the latest version if you want to try it.
  • The author does not provide any backward compatible guarantee at present.

Features

  • Requests-style APIs.
  • GET, POST, PUT, PATCH, DELETE, etc.
  • Easy set query params, headers and cookies.
  • Easy send form, JSON or multipart payload.
  • Easy set basic authentication or bearer token.
  • Easy set proxy.
  • Easy set context.
  • Backoff retry mechanism.
  • Automatic cookies management.
  • Request and response interceptors.
  • Reverse proxy.
  • Rate limiter for handling outbound requests.
  • Easy decode responses, raw data, text representation and unmarshal the JSON-encoded data.
  • Export curl command.
  • Friendly debugging.
  • Concurrent safe.

Install

go get -u github.com/winterssy/sreq

# Go Modules only
go get -u github.com/winterssy/sreq@master

Usage

import "github.com/winterssy/sreq"

Quick Start

The usages of sreq are very similar to net/http , you can switch from it to sreq easily. For example, if your HTTP request code like this:

resp, err := http.Get("https://www.google.com")

Use sreq you just need to change your code like this:

resp, err := sreq.Get("https://www.google.com").Raw()

You have two convenient ways to access the APIs of sreq .

const (
	url       = "http://httpbin.org/get"
	userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
)

query := sreq.Params{
	"k1": "v1",
	"k2": "v2",
}

client := sreq.New()

// Go-style
req, err := sreq.NewRequest("GET", url,
	sreq.WithQuery(query),
	sreq.WithUserAgent(userAgent),
)
if err != nil {
	panic(err)
}
err = client.
	Do(req).
	EnsureStatusOk().
	Verbose(ioutil.Discard, false)
if err != nil {
	panic(err)
}

// Requests-style (Recommended)
err = client.
	Get(url,
		sreq.WithQuery(query),
		sreq.WithUserAgent(userAgent),
	).
	EnsureStatusOk().
	Verbose(os.Stdout, true)
if err != nil {
	panic(err)
}

// Output:
// > GET /get?k1=v1&k2=v2 HTTP/1.1
// > Host: httpbin.org
// > User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
// >
// < HTTP/1.1 200 OK
// < Access-Control-Allow-Origin: *
// < Content-Type: application/json
// < Referrer-Policy: no-referrer-when-downgrade
// < Server: nginx
// < Access-Control-Allow-Credentials: true
// < Date: Mon, 02 Dec 2019 06:24:29 GMT
// < X-Content-Type-Options: nosniff
// < X-Frame-Options: DENY
// < X-Xss-Protection: 1; mode=block
// < Connection: keep-alive
// <
// {
//   "args": {
//     "k1": "v1",
//     "k2": "v2"
//   },
//   "headers": {
//     "Accept-Encoding": "gzip",
//     "Host": "httpbin.org",
//     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
//   },
//   "origin": "8.8.8.8, 8.8.8.8",
//   "url": "https://httpbin.org/get?k1=v1&k2=v2"
// }

Code examples

License

MIT

Documentation

Index

Constants

View Source
const (
	// MethodGet represents the GET method for HTTP.
	MethodGet = "GET"

	// MethodHead represents the HEAD method for HTTP.
	MethodHead = "HEAD"

	// MethodPost represents the POST method for HTTP.
	MethodPost = "POST"

	// MethodPut represents the PUT method for HTTP.
	MethodPut = "PUT"

	// MethodPatch represents the PATCH method for HTTP.
	MethodPatch = "PATCH"

	// MethodDelete represents the DELETE method for HTTP.
	MethodDelete = "DELETE"

	// MethodConnect represents the CONNECT method for HTTP.
	MethodConnect = "CONNECT"

	// MethodOptions represents the OPTIONS method for HTTP.
	MethodOptions = "OPTIONS"

	// MethodTrace represents the TRACE method for HTTP.
	MethodTrace = "TRACE"
)
View Source
const (
	// Version of sreq.
	Version = "0.9.11"
)

Variables

View Source
var (
	// ErrNilCookieJar can be used when the cookie jar is nil.
	ErrNilCookieJar = errors.New("sreq: nil cookie jar")

	// ErrNoCookie can be used when a cookie not found in the HTTP response or cookie jar.
	ErrNoCookie = errors.New("sreq: named cookie not present")
)
View Source
var (
	// DefaultBackoff specifies an exponential backoff with jitter
	// whose minWaitTime is 1s and maxWaitTime is 30s.
	DefaultBackoff = NewExponentialBackoff(1*time.Second, 30*time.Second, true)
)
View Source
var (
	// GlobalClient is a sreq Client used by the global functions such as Get, Post, etc.
	GlobalClient = New()
)

Functions

func DefaultTransport

func DefaultTransport() *http.Transport

DefaultTransport returns a preset HTTP transport. It's a clone of http.DefaultTransport indeed.

Types

type AfterResponseHook added in v0.8.16

type AfterResponseHook func(resp *Response) error

AfterResponseHook specifies an after response hook. If the returned error isn't nil, sreq will consider resp as a bad response.

type Backoff added in v0.8.15

type Backoff interface {
	// WaitTime returns the wait time to sleep before retrying request.
	WaitTime(attemptNum int, resp *Response) time.Duration
}

Backoff is the interface that specifies a backoff strategy for handling retries.

func NewExponentialBackoff added in v0.9.10

func NewExponentialBackoff(minWaitTime, maxWaitTime time.Duration, jitter bool) Backoff

NewExponentialBackoff provides a callback for the retry policy which will perform exponential backoff with jitter based on the attempt number and limited by the provided minimum and maximum durations. See: https://aws.amazon.com/cn/blogs/architecture/exponential-backoff-and-jitter/

type BeforeRequestHook added in v0.8.16

type BeforeRequestHook func(req *Request) error

BeforeRequestHook is alike to RequestOption, but for specifying a before request hook. Return a non-nil error to prevent requests.

func SetDefaultBasicAuth added in v0.8.17

func SetDefaultBasicAuth(username string, password string) BeforeRequestHook

SetDefaultBasicAuth is a before request hook to set client level basic authentication, can be overwrite by request level option.

func SetDefaultBearerToken added in v0.8.17

func SetDefaultBearerToken(token string) BeforeRequestHook

SetDefaultBearerToken is a before request hook to set client level bearer token, can be overwrite by request level option.

func SetDefaultContentType added in v0.8.17

func SetDefaultContentType(contentType string) BeforeRequestHook

SetDefaultContentType is a before request hook to set client level Content-Type header value, can be overwrite by request level option.

func SetDefaultCookies added in v0.8.17

func SetDefaultCookies(cookies Cookies) BeforeRequestHook

SetDefaultCookies is a before request hook to set client level cookies, can be overwrite by request level option.

func SetDefaultForm added in v0.8.17

func SetDefaultForm(form Form) BeforeRequestHook

SetDefaultForm is a before request hook to set client level form payload, can be overwrite by request level option.

func SetDefaultHeaders added in v0.8.17

func SetDefaultHeaders(headers Headers) BeforeRequestHook

SetDefaultHeaders is a before request hook to set client level headers, can be overwrite by request level option.

func SetDefaultHost added in v0.8.17

func SetDefaultHost(host string) BeforeRequestHook

SetDefaultHost is a before request hook set client level Host header value, can be overwrite by request level option.

func SetDefaultOrigin added in v0.9.9

func SetDefaultOrigin(origin string) BeforeRequestHook

SetDefaultOrigin is a before request hook to set client level Origin header value, can be overwrite by request level option.

func SetDefaultQuery added in v0.8.17

func SetDefaultQuery(query Params) BeforeRequestHook

SetDefaultQuery is a before request hook to set client level query parameters, can be overwrite by request level option.

func SetDefaultReferer added in v0.8.17

func SetDefaultReferer(referer string) BeforeRequestHook

SetDefaultReferer is a before request hook to set client level Referer header value, can be overwrite by request level option.

func SetDefaultRetry added in v0.8.17

func SetDefaultRetry(maxAttempts int, backoff Backoff, triggers ...func(resp *Response) bool) BeforeRequestHook

SetDefaultRetry is a before request hook to set client level retry policy, can be overwrite by request level option.

func SetDefaultUserAgent added in v0.8.17

func SetDefaultUserAgent(userAgent string) BeforeRequestHook

SetDefaultUserAgent is a before request hook to set client level User-Agent header value, can be overwrite by request level option.

func SetReverseProxy added in v0.9.9

func SetReverseProxy(target string, publicPaths ...string) BeforeRequestHook

SetReverseProxy is a before request hook to set reverse proxy for HTTP requests.

type Client

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

Client wraps the raw HTTP client. Do not modify the client across Goroutines! You should reuse it as possible after initialized.

func New

func New() *Client

New returns a new Client. It's a clone of GlobalClient indeed.

func NewWithHTTPClient added in v0.9.10

func NewWithHTTPClient(rawClient *http.Client) *Client

NewWithHTTPClient returns a new Client given an *http.Client.

func NewWithSession added in v0.9.10

func NewWithSession() *Client

NewWithSession is like New but with session support.

func (*Client) AppendClientCerts added in v0.7.11

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

AppendClientCerts appends client certificates to the HTTP client.

func (*Client) AppendRootCerts added in v0.7.12

func (c *Client) AppendRootCerts(pemFile string) *Client

AppendRootCerts appends root certificates from a pem file to the HTTP client. If there is an error while reading pemFile, it will panic.

func (*Client) Delete

func (c *Client) Delete(url string, opts ...RequestOption) *Response

Delete makes a DELETE HTTP request.

func (*Client) DisableProxy

func (c *Client) DisableProxy() *Client

DisableProxy makes the HTTP client not use proxy.

func (*Client) DisableRedirect

func (c *Client) DisableRedirect() *Client

DisableRedirect makes the HTTP client not follow redirects.

func (*Client) DisableVerify

func (c *Client) DisableVerify() *Client

DisableVerify makes the HTTP client not verify the server's TLS certificate.

func (*Client) Do

func (c *Client) Do(req *Request) *Response

Do sends a request and returns its response.

func (*Client) FilterCookie

func (c *Client) FilterCookie(url string, name string) (*http.Cookie, error)

FilterCookie returns the named cookie to send in a request for the given URL from cookie jar.

func (*Client) FilterCookies

func (c *Client) FilterCookies(url string) ([]*http.Cookie, error)

FilterCookies returns the cookies to send in a request for the given URL from cookie jar.

func (*Client) Get

func (c *Client) Get(url string, opts ...RequestOption) *Response

Get makes a GET HTTP request.

func (*Client) Head

func (c *Client) Head(url string, opts ...RequestOption) *Response

Head makes a HEAD HTTP request.

func (*Client) OnAfterResponse added in v0.8.16

func (c *Client) OnAfterResponse(hooks ...AfterResponseHook) *Client

OnAfterResponse appends response hooks into the after response chain.

func (*Client) OnBeforeRequest added in v0.8.16

func (c *Client) OnBeforeRequest(hooks ...BeforeRequestHook) *Client

OnBeforeRequest appends request hooks into the before request chain.

func (*Client) Patch

func (c *Client) Patch(url string, opts ...RequestOption) *Response

Patch makes a PATCH HTTP request.

func (*Client) Post

func (c *Client) Post(url string, opts ...RequestOption) *Response

Post makes a POST HTTP request.

func (*Client) Put

func (c *Client) Put(url string, opts ...RequestOption) *Response

Put makes a PUT HTTP request.

func (*Client) Send

func (c *Client) Send(method string, url string, opts ...RequestOption) *Response

Send makes an HTTP request using a specified method.

func (*Client) SetCookieJar

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

SetCookieJar sets cookie jar of the HTTP client.

func (*Client) SetCookies

func (c *Client) SetCookies(url string, cookies ...*http.Cookie) *Client

SetCookies sets cookies to cookie jar for the given URL. If the cookie jar is nil, it will panic.

func (*Client) SetProxy

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

SetProxy sets proxy of the HTTP client.

func (*Client) SetProxyFromURL

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

SetProxyFromURL sets proxy of the HTTP client from a URL.

func (*Client) SetRateLimiter added in v0.9.10

func (c *Client) SetRateLimiter(limiter *rate.Limiter, urlPatterns ...*regexp.Regexp) *Client

SetRateLimiter specifies a rate-limiter for c to handle outbound requests. If one or more urlPatterns are specified, only the URL matches one of the patterns will be limited.

func (*Client) SetRedirect

func (c *Client) SetRedirect(policy func(req *http.Request, via []*http.Request) error) *Client

SetRedirect sets policy of the HTTP client for handling redirects.

func (*Client) SetTLSClientConfig

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

SetTLSClientConfig sets TLS configuration of the HTTP client.

func (*Client) SetTimeout

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

SetTimeout sets timeout of the HTTP client, default is 120s.

func (*Client) SetTransport

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

SetTransport sets transport of the HTTP client.

type Cookies added in v0.8.8

type Cookies map[string]string

Cookies is a shortcut for map[string]string, used for request cookies.

func (Cookies) Clone added in v0.8.8

func (c Cookies) Clone() Cookies

Clone returns a copy of c or nil if c is nil.

func (Cookies) Decode added in v0.8.8

func (c Cookies) Decode() []*http.Cookie

Decode translates c and returns the equivalent request cookies.

func (Cookies) Del added in v0.8.8

func (c Cookies) Del(key string)

Del deletes the value associated with key.

func (Cookies) Get added in v0.8.8

func (c Cookies) Get(key string) *http.Cookie

Get gets the equivalent request cookie associated with key.

func (Cookies) Has added in v0.8.15

func (c Cookies) Has(key string) bool

Has checks if a key exists.

func (Cookies) Merge added in v0.8.8

func (c Cookies) Merge(c2 Cookies)

Merge merges c2 into c. It keeps the existing values.

func (Cookies) Set added in v0.8.8

func (c Cookies) Set(key string, value string)

Set sets the key to value. It replaces any existing values.

func (Cookies) SetDefault added in v0.8.8

func (c Cookies) SetDefault(key string, value string)

SetDefault sets the key to value if the value not exists.

func (Cookies) Update added in v0.8.8

func (c Cookies) Update(c2 Cookies)

Update merges c2 into c. It replaces any existing values.

type Error added in v0.9.2

type Error struct {
	Op  string
	Err error
}

Error records an error with more details to makes it more readable.

func (*Error) Error added in v0.9.2

func (e *Error) Error() string

Error implements error interface.

func (*Error) Unwrap added in v0.9.2

func (e *Error) Unwrap() error

Unwrap unpacks and returns the wrapped err of e.

type File added in v0.6.0

type File struct {
	Body io.Reader
	// contains filtered or unexported fields
}

File specifies a file to upload, it implements FormFile interface. Note: To upload a file its filename must be specified, if not, sreq will use "file" as default. If you don't specify the mime, sreq will detect automatically using http.DetectContentType.

func MustOpen added in v0.3.0

func MustOpen(filename string) *File

MustOpen opens the named file and returns a *File instance. If there is an error, it will panic.

func NewFile added in v0.6.0

func NewFile(body io.Reader, filename string) *File

NewFile returns a *File instance given the body and filename.

func Open added in v0.6.0

func Open(filename string) (*File, error)

Open opens the named file and returns a *File instance.

func (*File) Close added in v0.6.0

func (f *File) Close() error

Close implements Closer interface.

func (*File) Filename added in v0.6.0

func (f *File) Filename() string

Filename implements FormFile interface, returns the filename of f.

func (*File) MIME added in v0.6.0

func (f *File) MIME() string

MIME implements FormFile interface, returns the mine of f.

func (*File) Read added in v0.6.0

func (f *File) Read(p []byte) (int, error)

Read implements Reader interface.

func (*File) SetFilename added in v0.6.0

func (f *File) SetFilename(filename string) *File

SetFilename specifies the filename of f.

func (*File) SetMIME added in v0.6.0

func (f *File) SetMIME(mime string) *File

SetMIME specifies the mine of f.

type Files

type Files map[string]FormFile

Files maps a string key to a FormFile type value, used for form files of multipart payload.

func (Files) Del

func (f Files) Del(key string)

Del deletes the value associated with key.

func (Files) Get

func (f Files) Get(key string) FormFile

Get gets the value associated with key.

func (Files) Set

func (f Files) Set(key string, value FormFile)

Set sets the key to value. It replaces any existing values.

type Form

type Form = Values

Form is an alias of Values, used for request form data.

type FormFile added in v0.9.9

type FormFile interface {
	io.ReadCloser
	Filename() string
	MIME() string
}

FormFile is the interface that specifies a form file of multipart payload.

type H added in v0.7.0

type H map[string]interface{}

H is a shortcut for map[string]interface{}, used for JSON unmarshalling. Do not use it for other purposes!

func (H) Decode added in v0.8.7

func (h H) Decode(output interface{}) error

Decode encodes h to JSON and then decodes to the output structure. output must be a pointer.

func (H) Get added in v0.7.0

func (h H) Get(key string) interface{}

Get gets the interface{} value associated with key.

func (H) GetBool added in v0.7.0

func (h H) GetBool(key string) bool

GetBool gets the bool value associated with key. The zero value is returned if the key not exists.

func (H) GetBoolDefault added in v0.8.0

func (h H) GetBoolDefault(key string, defaultValue bool) bool

GetBoolDefault gets the bool value associated with key. The defaultValue is returned if the key not exists.

func (H) GetBoolSlice added in v0.7.0

func (h H) GetBoolSlice(key string) []bool

GetBoolSlice gets the []bool value associated with key.

func (H) GetH added in v0.7.0

func (h H) GetH(key string) H

GetH gets the H value associated with key.

func (H) GetHSlice added in v0.7.0

func (h H) GetHSlice(key string) []H

GetHSlice gets the []H value associated with key.

func (H) GetNumber added in v0.8.7

func (h H) GetNumber(key string) Number

GetNumber gets the Number value associated with key. The zero value is returned if the key not exists.

func (H) GetNumberDefault added in v0.8.7

func (h H) GetNumberDefault(key string, defaultValue Number) Number

GetNumberDefault gets the Number value associated with key. The defaultValue is returned if the key not exists.

func (H) GetNumberSlice added in v0.8.7

func (h H) GetNumberSlice(key string) []Number

GetNumberSlice gets the []Number value associated with key.

func (H) GetSlice added in v0.7.0

func (h H) GetSlice(key string) []interface{}

GetSlice gets the []interface{} value associated with key.

func (H) GetString added in v0.7.0

func (h H) GetString(key string) string

GetString gets the string value associated with key. The zero value is returned if the key not exists.

func (H) GetStringDefault added in v0.8.0

func (h H) GetStringDefault(key string, defaultValue string) string

GetStringDefault gets the string value associated with key. The defaultValue is returned if the key not exists.

func (H) GetStringSlice added in v0.7.0

func (h H) GetStringSlice(key string) []string

GetStringSlice gets the []string value associated with key.

func (H) Has added in v0.8.15

func (h H) Has(key string) bool

Has checks if a key exists.

func (H) String added in v0.7.0

func (h H) String() string

String returns the JSON-encoded text representation of h.

type Headers

type Headers = Values

Headers is an alias of Values, used for request headers.

type Number added in v0.8.7

type Number float64

Number is a shortcut for float64.

func (Number) Float32 added in v0.8.7

func (n Number) Float32() float32

Float32 converts n to a float32.

func (Number) Float64 added in v0.8.7

func (n Number) Float64() float64

Float64 converts n to a float64.

func (Number) Int added in v0.8.7

func (n Number) Int() int

Int converts n to an int.

func (Number) Int16 added in v0.8.7

func (n Number) Int16() int16

Int16 converts n to an int16.

func (Number) Int32 added in v0.8.7

func (n Number) Int32() int32

Int32 converts n to an int32.

func (Number) Int64 added in v0.8.7

func (n Number) Int64() int64

Int64 converts n to an int64.

func (Number) Int8 added in v0.8.7

func (n Number) Int8() int8

Int8 converts n to an int8.

func (Number) String added in v0.8.7

func (n Number) String() string

String converts n to a string.

func (Number) Uint added in v0.8.7

func (n Number) Uint() uint

Uint converts n to a uint.

func (Number) Uint16 added in v0.8.7

func (n Number) Uint16() uint16

Uint16 converts n to a uint16.

func (Number) Uint32 added in v0.8.7

func (n Number) Uint32() uint32

Uint32 converts n to a uint32.

func (Number) Uint64 added in v0.8.7

func (n Number) Uint64() uint64

Uint64 converts n to a uint64.

func (Number) Uint8 added in v0.8.7

func (n Number) Uint8() uint8

Uint8 converts n to a uint8.

type Params

type Params = Values

Params is an alias of Values, used for for request query parameters.

type Request

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

Request wraps the raw HTTP request.

func NewRequest

func NewRequest(method string, url string, opts ...RequestOption) (*Request, error)

NewRequest returns a new Request given a method, URL and optional request options.

func (*Request) Decode added in v0.9.7

func (req *Request) Decode() *http.Request

Decode translates req and returns the equivalent raw HTTP request.

func (*Request) Dump added in v0.9.9

func (req *Request) Dump(withBody bool) ([]byte, error)

Dump returns the HTTP/1.x wire representation of req.

func (*Request) ExportCURLCommand added in v0.9.10

func (req *Request) ExportCURLCommand() (string, error)

ExportCURLCommand converts req to CURL command line.

func (*Request) SetBasicAuth

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

SetBasicAuth sets basic authentication for the HTTP request.

func (*Request) SetBearerToken

func (req *Request) SetBearerToken(token string) *Request

SetBearerToken sets bearer token for the HTTP request.

func (*Request) SetBody

func (req *Request) SetBody(body io.Reader) *Request

SetBody sets body for the HTTP request.

func (*Request) SetContent

func (req *Request) SetContent(content []byte) *Request

SetContent sets bytes payload for the HTTP request.

func (*Request) SetContentType

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

SetContentType sets Content-Type header value for the HTTP request.

func (*Request) SetContext

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

SetContext sets context for the HTTP request.

func (*Request) SetCookies

func (req *Request) SetCookies(cookies Cookies) *Request

SetCookies sets cookies for the HTTP request.

func (*Request) SetForm

func (req *Request) SetForm(form Form) *Request

SetForm sets form payload for the HTTP request.

func (*Request) SetHeaders

func (req *Request) SetHeaders(headers Headers) *Request

SetHeaders sets headers for the HTTP request.

func (*Request) SetHost

func (req *Request) SetHost(host string) *Request

SetHost sets Host header value for the HTTP request.

func (*Request) SetJSON

func (req *Request) SetJSON(data interface{}, escapeHTML bool) error

SetJSON sets JSON payload for the HTTP request.

func (*Request) SetMultipart added in v0.3.0

func (req *Request) SetMultipart(files Files, form Form) *Request

SetMultipart sets multipart payload for the HTTP request.

func (*Request) SetOrigin added in v0.9.9

func (req *Request) SetOrigin(origin string) *Request

SetOrigin sets Origin header value for the HTTP request.

func (*Request) SetQuery

func (req *Request) SetQuery(query Params) *Request

SetQuery sets query parameters for the HTTP request.

func (*Request) SetReferer

func (req *Request) SetReferer(referer string) *Request

SetReferer sets Referer header value for the HTTP request.

func (*Request) SetRetry

func (req *Request) SetRetry(maxAttempts int, backoff Backoff, triggers ...func(resp *Response) bool) *Request

SetRetry specifies the retry policy for handling retries. The backoff is optional, default is DefaultBackoff.

func (*Request) SetText

func (req *Request) SetText(text string) *Request

SetText sets plain text payload for the HTTP request.

func (*Request) SetUserAgent

func (req *Request) SetUserAgent(userAgent string) *Request

SetUserAgent sets User-Agent header value for the HTTP request.

func (*Request) SetXML added in v0.6.0

func (req *Request) SetXML(data interface{}) error

SetXML sets XML payload for the HTTP request.

type RequestOption

type RequestOption func(req *Request) error

RequestOption provides a convenient way to setup Request.

func WithBasicAuth

func WithBasicAuth(username string, password string) RequestOption

WithBasicAuth is a request option to set basic authentication for the HTTP request.

func WithBearerToken

func WithBearerToken(token string) RequestOption

WithBearerToken is a request option to set bearer token for the HTTP request.

func WithBody

func WithBody(body io.Reader) RequestOption

WithBody is a request option to set body for the HTTP request.

func WithContent

func WithContent(content []byte) RequestOption

WithContent is a request option to set bytes payload for the HTTP request.

func WithContentType

func WithContentType(contentType string) RequestOption

WithContentType is a request option to set Content-Type header value for the HTTP request.

func WithContext

func WithContext(ctx context.Context) RequestOption

WithContext is a request option to set context for the HTTP request.

func WithCookies

func WithCookies(cookies Cookies) RequestOption

WithCookies is a request option to set cookies for the HTTP request.

func WithForm

func WithForm(form Form) RequestOption

WithForm is a request option to set form payload for the HTTP request.

func WithHeaders

func WithHeaders(headers Headers) RequestOption

WithHeaders is a request option to set headers for the HTTP request.

func WithHost

func WithHost(host string) RequestOption

WithHost is a request option to set Host header value for the HTTP request.

func WithJSON

func WithJSON(data interface{}, escapeHTML bool) RequestOption

WithJSON is a request option to set JSON payload for the HTTP request.

func WithMultipart added in v0.3.0

func WithMultipart(files Files, form Form) RequestOption

WithMultipart is a request option sets multipart payload for the HTTP request.

func WithOrigin added in v0.9.9

func WithOrigin(origin string) RequestOption

WithOrigin is a request option to set Origin header value for the HTTP request.

func WithQuery

func WithQuery(query Params) RequestOption

WithQuery is a request option to set query parameters for the HTTP request.

func WithReferer

func WithReferer(referer string) RequestOption

WithReferer is a request option to set Referer header value for the HTTP request.

func WithRetry

func WithRetry(maxAttempts int, backoff Backoff, triggers ...func(resp *Response) bool) RequestOption

WithRetry is a request option to specify the retry policy for handling retries.

func WithText

func WithText(text string) RequestOption

WithText is a request option to set plain text payload for the HTTP request.

func WithUserAgent

func WithUserAgent(userAgent string) RequestOption

WithUserAgent is a request option to set User-Agent header value for the HTTP request.

func WithXML added in v0.6.0

func WithXML(data interface{}) RequestOption

WithXML is a request option to set XML payload for the HTTP request.

type Response

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

Response wraps the raw HTTP response.

func Delete

func Delete(url string, opts ...RequestOption) *Response

Delete makes a DELETE HTTP request.

func Get

func Get(url string, opts ...RequestOption) *Response

Get makes a GET HTTP request.

func Head(url string, opts ...RequestOption) *Response

Head makes a HEAD HTTP request.

func Patch

func Patch(url string, opts ...RequestOption) *Response

Patch makes a PATCH HTTP request.

func Post

func Post(url string, opts ...RequestOption) *Response

Post makes a POST HTTP request.

func Put

func Put(url string, opts ...RequestOption) *Response

Put makes a PUT HTTP request.

func Send

func Send(method string, url string, opts ...RequestOption) *Response

Send makes an HTTP request using a specified method.

func (*Response) Content

func (resp *Response) Content() ([]byte, error)

Content decodes the HTTP response body to bytes.

func (*Response) Cookie

func (resp *Response) Cookie(name string) (*http.Cookie, error)

Cookie returns the HTTP response named cookie.

func (*Response) Cookies

func (resp *Response) Cookies() ([]*http.Cookie, error)

Cookies returns the HTTP response cookies.

func (*Response) Dump added in v0.9.10

func (resp *Response) Dump(withBody bool) ([]byte, error)

Dump returns the HTTP/1.x wire representation of resp.

func (*Response) EnsureStatus

func (resp *Response) EnsureStatus(code int) *Response

EnsureStatus ensures the HTTP response's status code must be code.

func (*Response) EnsureStatus2xx

func (resp *Response) EnsureStatus2xx() *Response

EnsureStatus2xx ensures the HTTP response's status code must be 2xx.

func (*Response) EnsureStatusOk

func (resp *Response) EnsureStatusOk() *Response

EnsureStatusOk ensures the HTTP response's status code must be 200.

func (*Response) Error added in v0.8.16

func (resp *Response) Error() error

Error reports resp's potential error.

func (*Response) H added in v0.7.0

func (resp *Response) H() (H, error)

H decodes the HTTP response body and unmarshals its JSON-encoded data into an H instance.

func (*Response) JSON

func (resp *Response) JSON(v interface{}) error

JSON decodes the HTTP response body and unmarshals its JSON-encoded data into v. v must be a pointer.

func (*Response) Prefetch added in v0.9.9

func (resp *Response) Prefetch() *Response

Prefetch reads from the HTTP response body until an error or EOF and keeps the data in memory for reuse.

func (*Response) Raw

func (resp *Response) Raw() (*http.Response, error)

Raw returns the raw HTTP response.

func (*Response) Save

func (resp *Response) Save(filename string, perm os.FileMode) error

Save saves the HTTP response into a file.

func (*Response) Text

func (resp *Response) Text(e ...encoding.Encoding) (string, error)

Text decodes the HTTP response body and returns the text representation of its raw data given an optional charset encoding.

func (*Response) Verbose

func (resp *Response) Verbose(w io.Writer, withBody bool) (err error)

Verbose makes the HTTP request and its response more talkative. It's similar to "curl -v", used for debug.

func (*Response) XML added in v0.6.0

func (resp *Response) XML(v interface{}) error

XML decodes the HTTP response body and unmarshals its XML-encoded data into v.

type Retry added in v0.8.17

type Retry struct {
	// MaxAttempts specifies the max attempts of the retry policy, 1 means no retries.
	MaxAttempts int

	// Backoff specifies the backoff of the retry policy. It is called
	// after a failing request to determine the amount of time
	// that should pass before trying again.
	Backoff Backoff

	// Triggers specifies a group of triggers for handling retries. It is called
	// following each request with the response values returned by Client.
	// If the triggers not specified, default is the error of resp isn't nil.
	// Otherwise, the Client will only retry the request when the response meets one of the triggers.
	Triggers []func(resp *Response) bool
}

Retry specifies the retry policy for handling retries.

type Values added in v0.6.0

type Values map[string]interface{}

Values maps a string key to an interface{} type value, When it's used for request query parameters, form data or headers, besides string and []string, its value also supports bool and number, sreq will convert to string automatically.

func (Values) Decode added in v0.8.8

func (v Values) Decode(canonicalHeaderKey bool) map[string][]string

Decode translates v and returns the equivalent request query parameters, form data or headers.

func (Values) Del added in v0.6.0

func (v Values) Del(key string)

Del deletes the value associated with key.

func (Values) Get added in v0.6.0

func (v Values) Get(key string) []string

Get gets the equivalent request query parameter, form data or header value associated with key.

func (Values) Has added in v0.8.15

func (v Values) Has(key string) bool

Has checks if a key exists.

func (Values) Marshal added in v0.7.10

func (v Values) Marshal() string

Marshal returns the JSON encoding of v.

func (Values) Merge added in v0.8.1

func (v Values) Merge(v2 Values)

Merge merges v2 into v. It keeps the existing values.

func (Values) Set added in v0.6.0

func (v Values) Set(key string, value interface{})

Set sets the key to value. It replaces any existing values.

func (Values) SetDefault added in v0.8.1

func (v Values) SetDefault(key string, value interface{})

SetDefault sets the key to value if the value not exists.

func (Values) URLEncode added in v0.9.3

func (v Values) URLEncode(escaped bool) string

URLEncode encodes v into URL form sorted by key when v is considered as request query parameters or form data.

func (Values) Update added in v0.8.3

func (v Values) Update(v2 Values)

Update merges v2 into v. It replaces any existing values.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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