sreq

package module
v0.0.0-...-6a183ee Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2021 License: MIT Imports: 27 Imported by: 0

README

sreq

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

Actions Status codecov Go Report Card GoDoc License

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("http://www.google.com")

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

resp, err := sreq.Get("http://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 timeout used by DefaultClient.
	DefaultTimeout = 120 * time.Second
)
View Source
const (
	// Version of sreq.
	Version = "0.7.5"
)

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

	// ErrNilContext can be used when the context is nil.
	ErrNilContext = errors.New("nil Context")

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

	// ErrJarCookiesNotPresent can be used when cookies for a given URL not present in cookie jar.
	ErrJarCookiesNotPresent = errors.New("sreq: cookies for the given URL not present")

	// ErrJarNamedCookieNotPresent can be used when named cookie for a given URL not present in cookie jar.
	ErrJarNamedCookieNotPresent = errors.New("sreq: named cookie for the given URL not present")

	// ErrResponseCookiesNotPresent can be used when cookies of the HTTP response not present.
	ErrResponseCookiesNotPresent = errors.New("sreq: cookies not present")

	// ErrResponseNamedCookieNotPresent can be used when named cookie of the HTTP response not present.
	ErrResponseNamedCookieNotPresent = errors.New("sreq: named cookie not present")
)
View Source
var (
	// DefaultClient is the default sreq Client,
	// used for the global functions such as Get, Post, etc.
	DefaultClient = New()
)

Functions

func DefaultTransport

func DefaultTransport() *http.Transport

DefaultTransport returns an HTTP transport used by DefaultClient. 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.

func FilterCookies

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

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

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 AppendClientCertificates

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

AppendClientCertificates appends client certificates to the HTTP client.

func AppendRootCAs

func AppendRootCAs(pemFilePath string) *Client

AppendRootCAs appends root certificate authorities 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 DefaultClient indeed.

func SetCookieJar

func SetCookieJar(jar http.CookieJar) *Client

SetCookieJar sets cookie jar of the HTTP client.

func SetProxy

func SetProxy(proxy func(*http.Request) (*stdurl.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 SetRetry

func SetRetry(attempts int, delay time.Duration,
	conditions ...func(*Response) bool) *Client

SetRetry sets retry policy of the client. The retry policy will be applied to all requests raised from this client instance. Also it can be overridden at request level retry policy options. Notes: Request timeout or context has priority over the retry policy.

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

func UseRequestInterceptors(interceptors ...RequestInterceptor) *Client

UseRequestInterceptors appends request interceptors of the client.

func UseResponseInterceptors

func UseResponseInterceptors(interceptors ...ResponseInterceptor) *Client

UseResponseInterceptors appends response interceptors of the client.

func (*Client) AppendClientCertificates

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

AppendClientCertificates appends client certificates to the HTTP client.

func (*Client) AppendRootCAs

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

AppendRootCAs appends root certificate authorities 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.

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.

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

func (c *Client) SetProxy(proxy func(*http.Request) (*stdurl.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) SetRetry

func (c *Client) SetRetry(attempts int, delay time.Duration,
	conditions ...func(*Response) bool) *Client

SetRetry sets retry policy of the client. The retry policy will be applied to all requests raised from this client instance. Also it can be overridden at request level retry policy options. Notes: Request timeout or context has priority over the retry policy.

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

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

UseRequestInterceptors appends request interceptors of the client.

func (*Client) UseResponseInterceptors

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 File

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 and then abort request. If you don't specify the MIME field, sreq will detect automatically using http.DetectContentType.

func MustOpen

func MustOpen(filename string) *File

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

func NewFile

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

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

func Open

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

Open opens the named file and returns a *File instance whose Filename is filename.

func (*File) Close

func (f *File) Close() error

Close implements Closer interface.

func (*File) Read

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

Read implements Reader interface.

func (*File) SetFilename

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

SetFilename sets Filename field value of f.

func (*File) SetMIME

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 values associated with key.

func (Files) Get

func (f Files) Get(key string) *File

Get gets the value associated with the given 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 form values.

type H

type H map[string]interface{}

H is a shortcut for map[string]interface{}, used for JSON unmarshalling.

func (H) Get

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

Get gets the interface{} value associated with the given key.

func (H) GetBool

func (h H) GetBool(key string) bool

GetBool gets the bool value associated with the given key.

func (H) GetBoolSlice

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

GetBoolSlice gets the []bool value associated with the given key.

func (H) GetFloat32

func (h H) GetFloat32(key string) float32

GetFloat32 gets the float32 value associated with the given key.

func (H) GetFloat32Slice

func (h H) GetFloat32Slice(key string) []float32

GetFloat32Slice gets the []float32 value associated with the given key.

func (H) GetFloat64

func (h H) GetFloat64(key string) float64

GetFloat64 gets the float64 value associated with the given key.

func (H) GetFloat64Slice

func (h H) GetFloat64Slice(key string) []float64

GetFloat64Slice gets the []float64 value associated with the given key.

func (H) GetH

func (h H) GetH(key string) H

GetH gets the H value associated with the given key.

func (H) GetHSlice

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

GetHSlice gets the []H value associated with the given key.

func (H) GetInt

func (h H) GetInt(key string) int

GetInt gets the int value associated with the given key.

func (H) GetInt32

func (h H) GetInt32(key string) int32

GetInt32 gets the int32 value associated with the given key.

func (H) GetInt32Slice

func (h H) GetInt32Slice(key string) []int32

GetInt32Slice gets the []int32 value associated with the given key.

func (H) GetInt64

func (h H) GetInt64(key string) int64

GetInt64 gets the int64 value associated with the given key.

func (H) GetInt64Slice

func (h H) GetInt64Slice(key string) []int64

GetInt64Slice gets the []int64 value associated with the given key.

func (H) GetIntSlice

func (h H) GetIntSlice(key string) []int

GetIntSlice gets the []int value associated with the given key.

func (H) GetSlice

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

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

func (H) GetString

func (h H) GetString(key string) string

GetString gets the string value associated with the given key.

func (H) GetStringSlice

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

GetStringSlice gets the []string value associated with the given key.

func (H) GetUint

func (h H) GetUint(key string) uint

GetUint gets the uint value associated with the given key.

func (H) GetUint32

func (h H) GetUint32(key string) uint32

GetUint32 gets the uint32 value associated with the given key.

func (H) GetUint32Slice

func (h H) GetUint32Slice(key string) []uint32

GetUint32Slice gets the []uint32 value associated with the given key.

func (H) GetUint64

func (h H) GetUint64(key string) uint64

GetUint64 gets the uint64 value associated with the given key.

func (H) GetUint64Slice

func (h H) GetUint64Slice(key string) []uint64

GetUint64Slice gets the []uint64 value associated with the given key.

func (H) GetUintSlice

func (h H) GetUintSlice(key string) []uint

GetUintSlice gets the []uint value associated with the given key.

func (H) String

func (h H) String() string

String returns the JSON-encoded text representation of h.

type Headers

type Headers map[string]interface{}

Headers maps a string key to an interface{} type value, support string, int, []string, []int or []interface{} only with string and int. Used for headers.

func (Headers) Del

func (h Headers) Del(key string)

Del deletes the values associated with key.

func (Headers) Get

func (h Headers) Get(key string) []string

Get gets the value associated with the given key, ignore unsupported data type.

func (Headers) Keys

func (h Headers) Keys() []string

Keys returns the keys of h.

func (Headers) Set

func (h Headers) Set(key string, value interface{})

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

func (Headers) String

func (h Headers) String() string

String returns the text representation of h.

type KV

type KV interface {
	Keys() []string
	Get(key string) []string
}

KV is the interface that defines a data type used by sreq in many cases. The Keys method should return a slice of keys typed string. The Get method should return a slice of values typed string associated with the given key.

type Params

type Params = Values

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

type Request

type Request struct {
	RawRequest *http.Request
	Err        error
	// 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 does 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 ...*http.Cookie) *Request

SetCookies sets cookies for the HTTP request.

func (*Request) SetForm

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

SetForm sets form payload for the HTTP request.

func (*Request) SetHeaders

func (req *Request) SetHeaders(headers KV) *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

func (req *Request) SetMultipart(files Files, form KV) *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 KV) *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 timeout or 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) SetTimeout

func (req *Request) SetTimeout(timeout time.Duration) *Request

SetTimeout sets timeout 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

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

type RequestInterceptor func(*Request) error

RequestInterceptor specifies a request interceptor.

type RequestOption

type RequestOption func(*Request) *Request

RequestOption specifies a request options, like params, form, etc.

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 does 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 ...*http.Cookie) RequestOption

WithCookies appends cookies for the HTTP request.

func WithForm

func WithForm(form KV) RequestOption

WithForm sets form payload for the HTTP request.

func WithHeaders

func WithHeaders(headers KV) 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

func WithMultipart(files Files, form KV) 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 KV) 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 timeout or context has priority over the retry policy.

func WithText

func WithText(text string) RequestOption

WithText sets plain text payload for the HTTP request.

func WithTimeout

func WithTimeout(timeout time.Duration) RequestOption

WithTimeout sets timeout for the HTTP request.

func WithUserAgent

func WithUserAgent(userAgent string) RequestOption

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

func WithXML

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

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.

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

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

func (*Response) XML

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

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

type ResponseInterceptor

type ResponseInterceptor func(*Response) error

ResponseInterceptor specifies a response interceptor.

type Values

type Values map[string]interface{}

Values maps a string key to an interface{} type value, support string, int, []string, []int or []interface{} only with string and int. Used for query parameters and form values.

func (Values) Del

func (v Values) Del(key string)

Del deletes the values associated with key.

func (Values) Encode

func (v Values) Encode() string

Encode encodes v into URL-unescaped form sorted by key.

func (Values) Get

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

Get gets the value associated with the given key, ignore unsupported data type.

func (Values) Keys

func (v Values) Keys() []string

Keys returns the keys of v.

func (Values) Set

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

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

func (Values) String

func (v Values) String() string

String returns the text representation of v.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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