sreq

package module
v0.8.11 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2020 License: MIT Imports: 27 Imported by: 15

README

sreq

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

Test 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.
  • Retry policy.
  • Automatic cookies management.
  • Request and response interceptors.
  • Easy decode responses, raw data, text representation and unmarshal the JSON-encoded data.
  • 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"
)

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

client := sreq.New()

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

// Requests-style (Recommended)
err = client.
	Get(url,
		sreq.WithQuery(params),
		sreq.WithUserAgent(userAgent),
	).
	EnsureStatusOk().
	Verbose(os.Stdout)
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 (
	// DefaultTimeout is the preset timeout.
	DefaultTimeout = 120 * time.Second
)
View Source
const (
	// Version of sreq.
	Version = "0.8.11"
)

Variables

View Source
var (
	// ErrUnexpectedTransport can be used if assert a RoundTripper as a non-nil *http.Transport instance failed.
	ErrUnexpectedTransport = errors.New("current transport isn't a non-nil *http.Transport instance")

	// ErrNilCookieJar can be used when the cookie jar is nil.
	ErrNilCookieJar = errors.New("nil cookie jar")

	// ErrNoCookie can be used when a cookie not found in the HTTP response or cookie jar.
	ErrNoCookie = errors.New("named cookie not present")
)
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.

func FilterCookie

func 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 FilterCookies

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

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

Types

type Client

type Client struct {
	RawClient *http.Client
	Err       error
	// 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 AppendClientCerts added in v0.7.11

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

AppendClientCerts appends client certificates to the HTTP client.

func AppendRootCerts added in v0.7.12

func AppendRootCerts(pemFile string) *Client

AppendRootCerts appends root certificates from a pem file to the HTTP client.

func DisableProxy

func DisableProxy() *Client

DisableProxy makes the HTTP client not use proxy.

func DisableRedirect

func DisableRedirect() *Client

DisableRedirect makes the HTTP client not follow redirects.

func DisableSession

func DisableSession() *Client

DisableSession makes the HTTP client not use cookie jar. Only use if you don't want to keep session for the next HTTP request.

func DisableVerify

func DisableVerify() *Client

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

func New

func New() *Client

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

func SetCookieJar

func SetCookieJar(jar http.CookieJar) *Client

SetCookieJar sets cookie jar of the HTTP client.

func SetCookies

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

SetCookies sets cookies to cookie jar for the given URL.

func SetProxy

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

SetProxy sets proxy of the HTTP client.

func SetProxyFromURL

func SetProxyFromURL(url string) *Client

SetProxyFromURL sets proxy of the HTTP client from a url.

func SetRedirect

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

SetRedirect sets policy of the HTTP client for handling redirects.

func SetTLSClientConfig

func SetTLSClientConfig(config *tls.Config) *Client

SetTLSClientConfig sets TLS configuration of the HTTP client.

func SetTimeout

func SetTimeout(timeout time.Duration) *Client

SetTimeout sets timeout of the HTTP client.

func SetTransport

func SetTransport(transport http.RoundTripper) *Client

SetTransport sets transport of the HTTP client.

func UseRequestInterceptors added in v0.2.0

func UseRequestInterceptors(interceptors ...RequestInterceptor) *Client

UseRequestInterceptors appends request interceptors of the client.

func UseResponseInterceptors added in v0.2.0

func UseResponseInterceptors(interceptors ...ResponseInterceptor) *Client

UseResponseInterceptors appends response interceptors of the client.

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.

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

func (c *Client) DisableSession() *Client

DisableSession makes the HTTP client not use cookie jar. Only use if you don't want to keep session for the next HTTP request.

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

func (c *Client) Raw() (*http.Client, error)

Raw returns the raw HTTP client.

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.

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

func (*Client) SetTransport

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

SetTransport sets transport of the HTTP client.

func (*Client) UseRequestInterceptors added in v0.2.0

func (c *Client) UseRequestInterceptors(interceptors ...RequestInterceptor) *Client

UseRequestInterceptors appends request interceptors of the client.

func (*Client) UseResponseInterceptors added in v0.2.0

func (c *Client) UseResponseInterceptors(interceptors ...ResponseInterceptor) *Client

UseResponseInterceptors appends response interceptors of the client.

type ClientError

type ClientError struct {
	Cause string
	Err   error
}

ClientError records a client error, can be used when sreq builds Client failed.

func (*ClientError) Error

func (c *ClientError) Error() string

Error implements error interface.

func (*ClientError) Unwrap

func (c *ClientError) Unwrap() error

Unwrap unpacks and returns the wrapped err of c.

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

Del deletes the value associated with key.

func (Cookies) Get added in v0.8.8

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

Get gets the equivalent request cookie associated with key.

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(name 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(name 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 File added in v0.6.0

type File struct {
	Filename string
	Body     io.Reader
	MIME     string
}

File specifies a file. To upload a file you must specify its Filename field, otherwise sreq will raise a *RequestError. If you don't specify the MIME field, 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(filename string, body io.Reader) *File

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

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) 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 sets Filename field value of f.

func (*File) SetMIME added in v0.6.0

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

SetMIME sets MIME field value of f.

type Files

type Files map[string]*File

Files maps a string key to a *File type value, used for 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) *File

Get gets the value associated with key.

func (Files) Set

func (f Files) Set(key string, value *File)

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 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) 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 {
	RawRequest *http.Request
	Err        error
	Body       io.Reader
	Host       string
	Headers    Headers
	Params     Params
	Form       Form
	Cookies    Cookies
	// contains filtered or unexported fields
}

Request wraps the raw HTTP request.

func NewRequest

func NewRequest(method string, url string) *Request

NewRequest returns a new Request given a method, URL.

func (*Request) Raw

func (req *Request) Raw() (*http.Request, error)

Raw returns the raw HTTP request.

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. Notes: SetBody may not support retry since it's unable to read a stream twice.

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 for the HTTP request.

func (*Request) SetJSON

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

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. Notes: SetMultipart does not support retry since it's unable to read a stream twice.

func (*Request) SetQuery

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

SetQuery sets query params 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(attempts int, delay time.Duration,
	conditions ...func(*Response) bool) *Request

SetRetry sets retry policy for the HTTP request. Notes: Request context has priority over the retry policy.

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{}) *Request

SetXML sets XML payload for the HTTP request.

type RequestError

type RequestError struct {
	Cause string
	Err   error
}

RequestError records a request error, can be used when sreq builds Request failed.

func (*RequestError) Error

func (req *RequestError) Error() string

Error implements error interface.

func (*RequestError) Unwrap

func (req *RequestError) Unwrap() error

Unwrap unpacks and returns the wrapped err of req.

type RequestInterceptor added in v0.2.0

type RequestInterceptor func(req *Request) error

RequestInterceptor specifies a request interceptor. If the returned error isn't nil, sreq will not send the request.

type RequestOption

type RequestOption func(req *Request) *Request

RequestOption specifies a request options, used to setup Request.

func WithBasicAuth

func WithBasicAuth(username string, password string) RequestOption

WithBasicAuth sets basic authentication for the HTTP request.

func WithBearerToken

func WithBearerToken(token string) RequestOption

WithBearerToken sets bearer token for the HTTP request.

func WithBody

func WithBody(body io.Reader) RequestOption

WithBody sets body for the HTTP request. Notes: WithBody may not support retry since it's unable to read a stream twice.

func WithContent

func WithContent(content []byte) RequestOption

WithContent sets bytes payload for the HTTP request.

func WithContentType

func WithContentType(contentType string) RequestOption

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

func WithContext

func WithContext(ctx context.Context) RequestOption

WithContext sets context for the HTTP request.

func WithCookies

func WithCookies(cookies Cookies) RequestOption

WithCookies appends cookies for the HTTP request.

func WithForm

func WithForm(form Form) RequestOption

WithForm sets form payload for the HTTP request.

func WithHeaders

func WithHeaders(headers Headers) RequestOption

WithHeaders sets headers for the HTTP request.

func WithHost

func WithHost(host string) RequestOption

WithHost sets host for the HTTP request.

func WithJSON

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

WithJSON sets JSON payload for the HTTP request.

func WithMultipart added in v0.3.0

func WithMultipart(files Files, form Form) RequestOption

WithMultipart sets multipart payload for the HTTP request. Notes: WithMultipart does not support retry since it's unable to read a stream twice.

func WithQuery

func WithQuery(params Params) RequestOption

WithQuery sets query params for the HTTP request.

func WithReferer

func WithReferer(referer string) RequestOption

WithReferer sets Referer header value for the HTTP request.

func WithRetry

func WithRetry(attempts int, delay time.Duration,
	conditions ...func(*Response) bool) RequestOption

WithRetry sets retry policy for the HTTP request. Notes: Request context has priority over the retry policy.

func WithText

func WithText(text string) RequestOption

WithText sets plain text payload for the HTTP request.

func WithUserAgent

func WithUserAgent(userAgent string) RequestOption

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

func WithXML added in v0.6.0

func WithXML(data interface{}) RequestOption

WithXML sets XML payload for the HTTP request.

type Response

type Response struct {
	RawResponse *http.Response
	Err         error
	// 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 Do

func Do(req *Request) *Response

Do sends a request and returns its response.

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

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

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

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) 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) 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. Notes: Save won't make the HTTP response body reusable.

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

Verbose makes the HTTP request and its response more talkative. It's similar to "curl -v", used for debug. Notes: Verbose won't make the HTTP response body reusable.

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 ResponseInterceptor added in v0.2.0

type ResponseInterceptor func(resp *Response) error

ResponseInterceptor specifies a response interceptor.

type Values added in v0.6.0

type Values map[string]interface{}

Values maps a string key to an interface{} type value, It's typically used for request query parameters, form data and headers.

func (Values) Decode added in v0.8.8

func (v Values) Decode() 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) Encode added in v0.6.0

func (v Values) Encode(urlEscaped bool) string

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

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