client

package
v0.0.0-...-372e6d2 Latest Latest
Warning

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

Go to latest
Published: May 6, 2025 License: MIT Imports: 31 Imported by: 0

README

Velocity Client

Easy-to-use HTTP client based on fasthttp (inspired by resty and axios)

Features section describes in detail about Resty capabilities

Features

The characteristics have not yet been written.

  • GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc.
  • Simple and chainable methods for settings and request
  • Request Body can be string, []byte, map, slice
    • Auto detects Content-Type
    • Buffer processing for files
    • Native *fasthttp.Request instance can be accessed during middleware and request execution via Request.RawRequest
    • Request Body can be read multiple time via Request.RawRequest.GetBody()
  • Response object gives you more possibility
    • Access as []byte by response.Body() or access as string by response.String()
  • Automatic marshal and unmarshal for JSON and XML content type
    • Default is JSON, if you supply struct/map without header Content-Type
    • For auto-unmarshal, refer to -
      • Success scenario Request.SetResult() and Response.Result().
      • Error scenario Request.SetError() and Response.Error().
      • Supports RFC7807 - application/problem+json & application/problem+xml
    • Provide an option to override JSON Marshal/Unmarshal and XML Marshal/Unmarshal

Usage

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

// Import Velocity Client into your code and refer it as `client`.
import "github.com/khulnasoft/velocity/client"

Simple GET

Documentation

Overview

The code was originally taken from https://github.com/valyala/fasthttp/pull/526.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTimeoutOrCancel      = errors.New("timeout or cancel")
	ErrURLFormat            = errors.New("the URL is incorrect")
	ErrNotSupportSchema     = errors.New("protocol not supported; only http or https are allowed")
	ErrFileNoName           = errors.New("the file should have a name")
	ErrBodyType             = errors.New("the body type should be []byte")
	ErrNotSupportSaveMethod = errors.New("only file paths and io.Writer are supported")
)
View Source
var ErrClientNil = errors.New("client cannot be nil")
View Source
var ErrFailedToAppendCert = errors.New("failed to append certificate")

Functions

func ReleaseCookieJar

func ReleaseCookieJar(c *CookieJar)

ReleaseCookieJar returns a CookieJar object to the pool.

func ReleaseFile

func ReleaseFile(f *File)

ReleaseFile returns the File object to the pool. Do not use the released File afterward to avoid data races.

func ReleaseRequest

func ReleaseRequest(req *Request)

ReleaseRequest returns the Request object to the pool. Do not use the released Request afterward to avoid data races.

func ReleaseResponse

func ReleaseResponse(resp *Response)

ReleaseResponse returns the Response object to the pool. Do not use the released Response afterward to avoid data races.

func Replace

func Replace(c *Client) func()

Replace replaces the defaultClient with a new one, returning a function to restore the old client.

func SetValWithStruct

func SetValWithStruct(p WithStruct, tagName string, v any)

SetValWithStruct sets values using a struct. The struct's fields are examined via reflection. `p` is a type that implements WithStruct. `tagName` defines the struct tag to look for. `v` is the struct containing data.

Fields in `v` should be string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128 or bool. Arrays or slices are inserted sequentially with the same key. Other types are ignored.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is used to create a Velocity client with client-level settings that apply to all requests made by the client.

The Velocity client also provides an option to override or merge most of the client settings at the request level.

func C

func C() *Client

C returns the default client.

func New

func New() *Client

New creates and returns a new Client object.

func NewWithClient

func NewWithClient(c *fasthttp.Client) *Client

NewWithClient creates and returns a new Client object from an existing fasthttp.Client.

func (*Client) AddHeader

func (c *Client) AddHeader(key, val string) *Client

AddHeader adds a single header field and its value to the client. These headers apply to all requests.

func (*Client) AddHeaders

func (c *Client) AddHeaders(h map[string][]string) *Client

AddHeaders adds multiple header fields and their values to the client.

func (*Client) AddParam

func (c *Client) AddParam(key, val string) *Client

AddParam adds a single query parameter and its value to the client. These params will be applied to all requests created from this client instance.

func (*Client) AddParams

func (c *Client) AddParams(m map[string][]string) *Client

AddParams adds multiple query parameters and their values to the client.

func (*Client) AddRequestHook

func (c *Client) AddRequestHook(h ...RequestHook) *Client

AddRequestHook adds user-defined request hooks.

func (*Client) AddResponseHook

func (c *Client) AddResponseHook(h ...ResponseHook) *Client

AddResponseHook adds user-defined response hooks.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the client's base URL.

func (*Client) CBORMarshal

func (c *Client) CBORMarshal() utils.CBORMarshal

CBORMarshal returns the CBOR marshal function used by the client.

func (*Client) CBORUnmarshal

func (c *Client) CBORUnmarshal() utils.CBORUnmarshal

CBORUnmarshal returns the CBOR unmarshal function used by the client.

func (*Client) Cookie

func (c *Client) Cookie(key string) string

Cookie returns the value of the specified cookie. Returns an empty string if it does not exist.

func (*Client) Custom

func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error)

Custom sends a request with a custom method to the specified URL, similar to axios.

func (*Client) Debug

func (c *Client) Debug() *Client

Debug enables debug-level logging output.

func (*Client) DelCookies

func (c *Client) DelCookies(key ...string) *Client

DelCookies deletes one or more cookies and their values from the client.

func (*Client) DelParams

func (c *Client) DelParams(key ...string) *Client

DelParams deletes one or more query parameters and their values from the client.

func (*Client) DelPathParams

func (c *Client) DelPathParams(key ...string) *Client

DelPathParams deletes one or more path parameters and their values from the client.

func (*Client) Delete

func (c *Client) Delete(url string, cfg ...Config) (*Response, error)

Delete sends a DELETE request to the specified URL, similar to axios.

func (*Client) DisableDebug

func (c *Client) DisableDebug() *Client

DisableDebug disables debug-level logging output.

func (*Client) Get

func (c *Client) Get(url string, cfg ...Config) (*Response, error)

Get sends a GET request to the specified URL, similar to axios.

func (*Client) Head

func (c *Client) Head(url string, cfg ...Config) (*Response, error)

Head sends a HEAD request to the specified URL, similar to axios.

func (*Client) Header

func (c *Client) Header(key string) []string

Header returns all header values associated with the provided key.

func (*Client) JSONMarshal

func (c *Client) JSONMarshal() utils.JSONMarshal

JSONMarshal returns the JSON marshal function used by the client.

func (*Client) JSONUnmarshal

func (c *Client) JSONUnmarshal() utils.JSONUnmarshal

JSONUnmarshal returns the JSON unmarshal function used by the client.

func (*Client) Logger

func (c *Client) Logger() log.CommonLogger

Logger returns the logger instance used by the client.

func (*Client) Options

func (c *Client) Options(url string, cfg ...Config) (*Response, error)

Options sends an OPTIONS request to the specified URL, similar to axios.

func (*Client) Param

func (c *Client) Param(key string) []string

Param returns all values of the specified query parameter.

func (*Client) Patch

func (c *Client) Patch(url string, cfg ...Config) (*Response, error)

Patch sends a PATCH request to the specified URL, similar to axios.

func (*Client) PathParam

func (c *Client) PathParam(key string) string

PathParam returns the value of the specified path parameter. Returns an empty string if it does not exist.

func (*Client) Post

func (c *Client) Post(url string, cfg ...Config) (*Response, error)

Post sends a POST request to the specified URL, similar to axios.

func (*Client) Put

func (c *Client) Put(url string, cfg ...Config) (*Response, error)

Put sends a PUT request to the specified URL, similar to axios.

func (*Client) R

func (c *Client) R() *Request

R creates a new Request associated with the client.

func (*Client) RequestHook

func (c *Client) RequestHook() []RequestHook

RequestHook returns the user-defined request hooks.

func (*Client) Reset

func (c *Client) Reset()

Reset resets the client to its default state, clearing most configurations.

func (*Client) ResponseHook

func (c *Client) ResponseHook() []ResponseHook

ResponseHook returns the user-defined response hooks.

func (*Client) RetryConfig

func (c *Client) RetryConfig() *RetryConfig

RetryConfig returns the current retry configuration.

func (*Client) SetBaseURL

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

SetBaseURL sets the base URL prefix for all requests made by the client.

func (*Client) SetCBORMarshal

func (c *Client) SetCBORMarshal(f utils.CBORMarshal) *Client

SetCBORMarshal sets the CBOR marshal function to use.

func (*Client) SetCBORUnmarshal

func (c *Client) SetCBORUnmarshal(f utils.CBORUnmarshal) *Client

SetCBORUnmarshal sets the CBOR unmarshal function to use.

func (*Client) SetCertificates

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

SetCertificates adds certificates to the client's TLS configuration.

func (*Client) SetCookie

func (c *Client) SetCookie(key, val string) *Client

SetCookie sets a single cookie and its value in the client.

func (*Client) SetCookieJar

func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client

SetCookieJar sets the cookie jar for the client.

func (*Client) SetCookies

func (c *Client) SetCookies(m map[string]string) *Client

SetCookies sets multiple cookies and their values in the client.

func (*Client) SetCookiesWithStruct

func (c *Client) SetCookiesWithStruct(v any) *Client

SetCookiesWithStruct sets multiple cookies and their values using a struct.

func (*Client) SetDial

func (c *Client) SetDial(dial fasthttp.DialFunc) *Client

SetDial sets the custom dial function for the client.

func (*Client) SetHeader

func (c *Client) SetHeader(key, val string) *Client

SetHeader sets a single header field and its value in the client.

func (*Client) SetHeaders

func (c *Client) SetHeaders(h map[string]string) *Client

SetHeaders method sets multiple headers field and its values at one go in the client instance. These headers will be applied to all requests created from this client instance. Also it can be overridden at request level headers options.

func (*Client) SetJSONMarshal

func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client

SetJSONMarshal sets the JSON marshal function to use.

func (*Client) SetJSONUnmarshal

func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client

SetJSONUnmarshal sets the JSON unmarshal function to use.

func (*Client) SetLogger

func (c *Client) SetLogger(logger log.CommonLogger) *Client

SetLogger sets the logger instance used by the client.

func (*Client) SetParam

func (c *Client) SetParam(key, val string) *Client

SetParam sets a single query parameter and its value in the client.

func (*Client) SetParams

func (c *Client) SetParams(m map[string]string) *Client

SetParams sets multiple query parameters and their values in the client.

func (*Client) SetParamsWithStruct

func (c *Client) SetParamsWithStruct(v any) *Client

SetParamsWithStruct sets multiple query parameters and their values using a struct.

func (*Client) SetPathParam

func (c *Client) SetPathParam(key, val string) *Client

SetPathParam sets a single path parameter and its value in the client.

func (*Client) SetPathParams

func (c *Client) SetPathParams(m map[string]string) *Client

SetPathParams sets multiple path parameters and their values in the client.

func (*Client) SetPathParamsWithStruct

func (c *Client) SetPathParamsWithStruct(v any) *Client

SetPathParamsWithStruct sets multiple path parameters and their values using a struct.

func (*Client) SetProxyURL

func (c *Client) SetProxyURL(proxyURL string) error

SetProxyURL sets the proxy URL for the client. This affects all subsequent requests.

func (*Client) SetReferer

func (c *Client) SetReferer(r string) *Client

SetReferer sets the Referer header for the client.

func (*Client) SetRetryConfig

func (c *Client) SetRetryConfig(config *RetryConfig) *Client

SetRetryConfig sets the retry configuration for the client.

func (*Client) SetRootCertificate

func (c *Client) SetRootCertificate(path string) *Client

SetRootCertificate adds one or more root certificates to the client's TLS configuration.

func (*Client) SetRootCertificateFromString

func (c *Client) SetRootCertificateFromString(pem string) *Client

SetRootCertificateFromString adds one or more root certificates from a string to the client's TLS configuration.

func (*Client) SetTLSConfig

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

SetTLSConfig sets the TLS configuration for the client.

func (*Client) SetTimeout

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

SetTimeout sets the timeout value for the client. This applies to all requests unless overridden at the request level.

func (*Client) SetUserAgent

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

SetUserAgent sets the User-Agent header for the client.

func (*Client) SetXMLMarshal

func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client

SetXMLMarshal sets the XML marshal function to use.

func (*Client) SetXMLUnmarshal

func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client

SetXMLUnmarshal sets the XML unmarshal function to use.

func (*Client) TLSConfig

func (c *Client) TLSConfig() *tls.Config

TLSConfig returns the client's TLS configuration. If none is set, it initializes a new one.

func (*Client) XMLMarshal

func (c *Client) XMLMarshal() utils.XMLMarshal

XMLMarshal returns the XML marshal function used by the client.

func (*Client) XMLUnmarshal

func (c *Client) XMLUnmarshal() utils.XMLUnmarshal

XMLUnmarshal returns the XML unmarshal function used by the client.

type Config

type Config struct {
	Ctx          context.Context //nolint:containedctx // It's needed to be stored in the config.
	Body         any
	Header       map[string]string
	Param        map[string]string
	Cookie       map[string]string
	PathParam    map[string]string
	FormData     map[string]string
	UserAgent    string
	Referer      string
	File         []*File
	Timeout      time.Duration
	MaxRedirects int
}

Config is used to easily set request parameters. Note that when setting a request body, JSON is used as the default serialization mechanism. The priority is: Body > FormData > File.

type Cookie map[string]string

Cookie is a map used to store cookies.

func (Cookie) Add

func (c Cookie) Add(key, val string)

Add adds a cookie key-value pair.

func (Cookie) Del

func (c Cookie) Del(key string)

Del deletes a cookie by key.

func (Cookie) DelCookies

func (c Cookie) DelCookies(key ...string)

DelCookies deletes multiple cookies by keys.

func (Cookie) Reset

func (c Cookie) Reset()

Reset clears the Cookie map.

func (Cookie) SetCookie

func (c Cookie) SetCookie(key, val string)

SetCookie sets a single cookie value.

func (Cookie) SetCookies

func (c Cookie) SetCookies(m map[string]string)

SetCookies sets multiple cookies from a map.

func (Cookie) SetCookiesWithStruct

func (c Cookie) SetCookiesWithStruct(v any)

SetCookiesWithStruct sets cookies from a struct. Nested structs are not currently supported.

func (Cookie) VisitAll

func (c Cookie) VisitAll(f func(key, val string))

VisitAll iterates through all cookies, calling f for each.

type CookieJar

type CookieJar struct {
	// contains filtered or unexported fields
}

CookieJar manages cookie storage for the client. It stores cookies keyed by host.

func AcquireCookieJar

func AcquireCookieJar() *CookieJar

AcquireCookieJar returns an empty CookieJar object from the pool.

func (*CookieJar) Get

func (cj *CookieJar) Get(uri *fasthttp.URI) []*fasthttp.Cookie

Get returns all cookies stored for a given URI. If there are no cookies for the provided host, the returned slice will be nil.

The CookieJar keeps its own copies of cookies, so it is safe to release the returned cookies after use.

func (*CookieJar) Release

func (cj *CookieJar) Release()

Release releases all stored cookies. After this, the CookieJar is empty.

func (*CookieJar) Set

func (cj *CookieJar) Set(uri *fasthttp.URI, cookies ...*fasthttp.Cookie)

Set stores the given cookies for the specified URI host. If a cookie key already exists, it will be replaced by the new cookie value.

CookieJar stores copies of the provided cookies, so they may be safely released after use.

func (*CookieJar) SetByHost

func (cj *CookieJar) SetByHost(host []byte, cookies ...*fasthttp.Cookie)

SetByHost stores the given cookies for the specified host. If a cookie key already exists, it will be replaced by the new cookie value.

CookieJar stores copies of the provided cookies, so they may be safely released after use.

func (*CookieJar) SetKeyValue

func (cj *CookieJar) SetKeyValue(host, key, value string)

SetKeyValue sets a cookie for the specified host with the given key and value.

This function helps prevent extra allocations by avoiding duplication of repeated cookies.

func (*CookieJar) SetKeyValueBytes

func (cj *CookieJar) SetKeyValueBytes(host string, key, value []byte)

SetKeyValueBytes sets a cookie for the specified host using byte slices for the key and value.

This function helps prevent extra allocations by avoiding duplication of repeated cookies.

type File

type File struct {
	// contains filtered or unexported fields
}

File represents a file to be sent with the request.

func AcquireFile

func AcquireFile(setter ...SetFileFunc) *File

AcquireFile returns a (pooled) File object and applies the provided SetFileFunc functions to it.

func (*File) Reset

func (f *File) Reset()

Reset clears the File object.

func (*File) SetFieldName

func (f *File) SetFieldName(n string)

SetFieldName sets the key associated with the file in the body.

func (*File) SetName

func (f *File) SetName(n string)

SetName sets the file's name.

func (*File) SetPath

func (f *File) SetPath(p string)

SetPath sets the file's path.

func (*File) SetReader

func (f *File) SetReader(r io.ReadCloser)

SetReader sets the file's reader, which will be closed in the parserBody hook.

type FormData

type FormData struct {
	*fasthttp.Args
}

FormData wraps fasthttp.Args for URL-encoded bodies and form data.

func (*FormData) Add

func (f *FormData) Add(key, val string)

Add adds a single form field.

func (*FormData) AddWithMap

func (f *FormData) AddWithMap(m map[string][]string)

AddWithMap adds multiple form fields from a map.

func (*FormData) DelData

func (f *FormData) DelData(key ...string)

DelData deletes multiple form fields.

func (*FormData) Keys

func (f *FormData) Keys() []string

Keys returns all keys from the form data.

func (*FormData) Reset

func (f *FormData) Reset()

Reset clears the FormData object.

func (*FormData) Set

func (f *FormData) Set(key, val string)

Set sets a single form field, overriding previously set values.

func (*FormData) SetWithMap

func (f *FormData) SetWithMap(m map[string]string)

SetWithMap sets multiple form fields from a map, overriding previously set values.

func (*FormData) SetWithStruct

func (f *FormData) SetWithStruct(v any)

SetWithStruct sets multiple form fields from a struct. Nested structs are not currently supported.

type Header struct {
	*fasthttp.RequestHeader
}

Header wraps fasthttp.RequestHeader, storing headers for both client and request.

func (*Header) AddHeaders

func (h *Header) AddHeaders(r map[string][]string)

AddHeaders adds multiple headers from a map.

func (*Header) PeekMultiple

func (h *Header) PeekMultiple(key string) []string

PeekMultiple returns multiple values of a header field with the same key.

func (*Header) SetHeaders

func (h *Header) SetHeaders(r map[string]string)

SetHeaders sets multiple headers from a map, overriding previously set values.

type PathParam

type PathParam map[string]string

PathParam is a map used to store path parameters.

func (PathParam) Add

func (p PathParam) Add(key, val string)

Add adds a path parameter key-value pair.

func (PathParam) Del

func (p PathParam) Del(key string)

Del deletes a path parameter by key.

func (PathParam) DelParams

func (p PathParam) DelParams(key ...string)

DelParams deletes multiple path parameters.

func (PathParam) Reset

func (p PathParam) Reset()

Reset clears the PathParam map.

func (PathParam) SetParam

func (p PathParam) SetParam(key, val string)

SetParam sets a single path parameter.

func (PathParam) SetParams

func (p PathParam) SetParams(m map[string]string)

SetParams sets multiple path parameters from a map.

func (PathParam) SetParamsWithStruct

func (p PathParam) SetParamsWithStruct(v any)

SetParamsWithStruct sets multiple path parameters from a struct. Nested structs are not currently supported.

func (PathParam) VisitAll

func (p PathParam) VisitAll(f func(key, val string))

VisitAll iterates through all path parameters, calling f for each.

type QueryParam

type QueryParam struct {
	*fasthttp.Args
}

QueryParam wraps fasthttp.Args for query parameters.

func (*QueryParam) AddParams

func (p *QueryParam) AddParams(r map[string][]string)

AddParams adds multiple parameters from a map.

func (*QueryParam) Keys

func (p *QueryParam) Keys() []string

Keys returns all keys from the query parameters.

func (*QueryParam) SetParams

func (p *QueryParam) SetParams(r map[string]string)

SetParams sets multiple parameters from a map, overriding previously set values.

func (*QueryParam) SetParamsWithStruct

func (p *QueryParam) SetParamsWithStruct(v any)

SetParamsWithStruct sets multiple parameters from a struct. Nested structs are not currently supported.

type Request

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

Request contains all data related to an HTTP request.

func AcquireRequest

func AcquireRequest() *Request

AcquireRequest returns a new (pooled) Request object.

func (*Request) AddFile

func (r *Request) AddFile(path string) *Request

AddFile adds a single file by its path.

func (*Request) AddFileWithReader

func (r *Request) AddFileWithReader(name string, reader io.ReadCloser) *Request

AddFileWithReader adds a file using an io.ReadCloser.

func (*Request) AddFiles

func (r *Request) AddFiles(files ...*File) *Request

AddFiles adds multiple files at once.

func (*Request) AddFormData

func (r *Request) AddFormData(key, val string) *Request

AddFormData adds a single form field and value to the Request.

func (*Request) AddFormDataWithMap

func (r *Request) AddFormDataWithMap(m map[string][]string) *Request

AddFormDataWithMap adds multiple form fields and values to the Request.

func (*Request) AddHeader

func (r *Request) AddHeader(key, val string) *Request

AddHeader adds a single header field and value to the Request.

func (*Request) AddHeaders

func (r *Request) AddHeaders(h map[string][]string) *Request

AddHeaders adds multiple header fields and values at once.

func (*Request) AddParam

func (r *Request) AddParam(key, val string) *Request

AddParam adds a single query parameter and value to the Request.

func (*Request) AddParams

func (r *Request) AddParams(m map[string][]string) *Request

AddParams adds multiple query parameters and their values at once.

func (*Request) AllFormData

func (r *Request) AllFormData() iter.Seq2[string, []string]

AllFormData returns an iterator over all form fields. Use maps.Collect() to gather them into a map if needed.

The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.

func (*Request) Boundary

func (r *Request) Boundary() string

Boundary returns the multipart boundary used by the Request.

func (*Request) Client

func (r *Request) Client() *Client

Client returns the Client instance associated with this Request.

func (*Request) Context

func (r *Request) Context() context.Context

Context returns the context associated with the Request. If not set, a background context is returned.

func (*Request) Cookie

func (r *Request) Cookie(key string) string

Cookie returns the value of a named cookie. If the cookie does not exist, an empty string is returned.

func (*Request) Cookies

func (r *Request) Cookies() iter.Seq2[string, string]

Cookies returns an iterator over all cookies. Use maps.Collect() to gather them into a map if needed.

func (*Request) Custom

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

Custom sends a request with a custom HTTP method to the given URL.

func (*Request) DelCookies

func (r *Request) DelCookies(key ...string) *Request

DelCookies deletes one or more cookies.

func (*Request) DelFormData

func (r *Request) DelFormData(key ...string) *Request

DelFormData deletes one or more form fields.

func (*Request) DelParams

func (r *Request) DelParams(key ...string) *Request

DelParams deletes one or more query parameters.

func (*Request) DelPathParams

func (r *Request) DelPathParams(key ...string) *Request

DelPathParams deletes one or more path parameters.

func (*Request) Delete

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

Delete sends a DELETE request to the given URL.

func (*Request) File

func (r *Request) File(name string) *File

File returns the file associated with the given name. If no name was provided during addition, it attempts to match by the file's base name.

func (*Request) FileByPath

func (r *Request) FileByPath(path string) *File

FileByPath returns the file associated with the given file path.

func (*Request) Files

func (r *Request) Files() []*File

Files returns all files added to the Request.

The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.

func (*Request) FormData

func (r *Request) FormData(key string) []string

FormData returns all values associated with a form field.

func (*Request) Get

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

Get sends a GET request to the given URL.

func (*Request) Head

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

Head sends a HEAD request to the given URL.

func (*Request) Header

func (r *Request) Header(key string) []string

Header returns all values associated with the given header key.

func (*Request) Headers

func (r *Request) Headers() iter.Seq2[string, []string]

Headers returns an iterator over all headers in the Request. Use maps.Collect() to gather them into a map if needed.

The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.

func (*Request) MaxRedirects

func (r *Request) MaxRedirects() int

MaxRedirects returns the maximum number of redirects configured for the Request.

func (*Request) Method

func (r *Request) Method() string

Method returns the HTTP method set in the Request.

func (*Request) Options

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

Options sends an OPTIONS request to the given URL.

func (*Request) Param

func (r *Request) Param(key string) []string

Param returns all values associated with the given query parameter.

func (*Request) Params

func (r *Request) Params() iter.Seq2[string, []string]

Params returns an iterator over all query parameters in the Request. Use maps.Collect() to gather them into a map if needed.

The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.

func (*Request) Patch

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

Patch sends a PATCH request to the given URL.

func (*Request) PathParam

func (r *Request) PathParam(key string) string

PathParam returns the value of a named path parameter. If the parameter does not exist, an empty string is returned.

func (*Request) PathParams

func (r *Request) PathParams() iter.Seq2[string, string]

PathParams returns an iterator over all path parameters. Use maps.Collect() to gather them into a map if needed.

func (*Request) Post

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

Post sends a POST request to the given URL.

func (*Request) Put

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

Put sends a PUT request to the given URL.

func (*Request) Referer

func (r *Request) Referer() string

Referer returns the Referer header set in the Request.

func (*Request) Reset

func (r *Request) Reset()

Reset clears the Request object, returning it to its default state. Used by ReleaseRequest to recycle the object.

func (*Request) ResetPathParams

func (r *Request) ResetPathParams() *Request

ResetPathParams deletes all path parameters.

func (*Request) Send

func (r *Request) Send() (*Response, error)

Send executes the Request.

func (*Request) SetBoundary

func (r *Request) SetBoundary(b string) *Request

SetBoundary sets the multipart boundary.

func (*Request) SetCBOR

func (r *Request) SetCBOR(v any) *Request

SetCBOR sets the request body to a CBOR-encoded value.

func (*Request) SetClient

func (r *Request) SetClient(c *Client) *Request

SetClient sets the Client instance for the Request.

func (*Request) SetContext

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

SetContext sets the context for the Request, allowing request cancellation if ctx is done. See https://blog.golang.org/context article and the "context" package documentation.

func (*Request) SetCookie

func (r *Request) SetCookie(key, val string) *Request

SetCookie sets a single cookie, overriding any previously set value.

func (*Request) SetCookies

func (r *Request) SetCookies(m map[string]string) *Request

SetCookies sets multiple cookies at once, overriding previously set values.

func (*Request) SetCookiesWithStruct

func (r *Request) SetCookiesWithStruct(v any) *Request

SetCookiesWithStruct sets multiple cookies from a struct, overriding previously set values.

func (*Request) SetFormData

func (r *Request) SetFormData(key, val string) *Request

SetFormData sets a single form field and value, overriding any previously set value.

func (*Request) SetFormDataWithMap

func (r *Request) SetFormDataWithMap(m map[string]string) *Request

SetFormDataWithMap sets multiple form fields and values at once, overriding previously set values.

func (*Request) SetFormDataWithStruct

func (r *Request) SetFormDataWithStruct(v any) *Request

SetFormDataWithStruct sets multiple form fields from a struct, overriding previously set values.

func (*Request) SetHeader

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

SetHeader sets a single header field and value in the Request, overriding any previously set value.

func (*Request) SetHeaders

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

SetHeaders sets multiple header fields and values at once, overriding previously set values.

func (*Request) SetJSON

func (r *Request) SetJSON(v any) *Request

SetJSON sets the request body to a JSON-encoded value.

func (*Request) SetMaxRedirects

func (r *Request) SetMaxRedirects(count int) *Request

SetMaxRedirects sets the maximum number of redirects, overriding any previously set value.

func (*Request) SetMethod

func (r *Request) SetMethod(method string) *Request

SetMethod sets the HTTP method for the Request. It is recommended to use the specialized methods (e.g., Get, Post) instead.

func (*Request) SetParam

func (r *Request) SetParam(key, val string) *Request

SetParam sets a single query parameter and value in the Request, overriding any previously set value.

func (*Request) SetParams

func (r *Request) SetParams(m map[string]string) *Request

SetParams sets multiple query parameters and their values at once, overriding previously set values.

func (*Request) SetParamsWithStruct

func (r *Request) SetParamsWithStruct(v any) *Request

SetParamsWithStruct sets multiple query parameters from a struct, overriding previously set values.

func (*Request) SetPathParam

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

SetPathParam sets a single path parameter and value, overriding any previously set value.

func (*Request) SetPathParams

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

SetPathParams sets multiple path parameters and values at once, overriding previously set values.

func (*Request) SetPathParamsWithStruct

func (r *Request) SetPathParamsWithStruct(v any) *Request

SetPathParamsWithStruct sets multiple path parameters from a struct, overriding previously set values.

func (*Request) SetRawBody

func (r *Request) SetRawBody(v []byte) *Request

SetRawBody sets the request body to raw bytes.

func (*Request) SetReferer

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

SetReferer sets the Referer header, overriding any previously set value.

func (*Request) SetTimeout

func (r *Request) SetTimeout(t time.Duration) *Request

SetTimeout sets the timeout for the Request, overriding any previously set value.

func (*Request) SetURL

func (r *Request) SetURL(url string) *Request

SetURL sets the URL for the Request.

func (*Request) SetUserAgent

func (r *Request) SetUserAgent(ua string) *Request

SetUserAgent sets the User-Agent header, overriding any previously set value.

func (*Request) SetXML

func (r *Request) SetXML(v any) *Request

SetXML sets the request body to an XML-encoded value.

func (*Request) Timeout

func (r *Request) Timeout() time.Duration

Timeout returns the timeout duration set in the Request.

func (*Request) URL

func (r *Request) URL() string

URL returns the URL set in the Request.

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns the User-Agent header set in the Request.

type RequestHook

type RequestHook func(*Client, *Request) error

RequestHook is a function invoked before the request is sent. It receives a Client and a Request, allowing you to modify the Request or Client data.

type Response

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

Response represents the result of a request. It provides access to the response data.

func AcquireResponse

func AcquireResponse() *Response

AcquireResponse returns a new (pooled) Response object. When done, release it with ReleaseResponse to reduce GC load.

func Delete

func Delete(url string, cfg ...Config) (*Response, error)

Delete sends a DELETE request using the default client.

func Get

func Get(url string, cfg ...Config) (*Response, error)

Get sends a GET request using the default client.

func Head(url string, cfg ...Config) (*Response, error)

Head sends a HEAD request using the default client.

func Options

func Options(url string, cfg ...Config) (*Response, error)

Options sends an OPTIONS request using the default client.

func Patch

func Patch(url string, cfg ...Config) (*Response, error)

Patch sends a PATCH request using the default client.

func Post

func Post(url string, cfg ...Config) (*Response, error)

Post sends a POST request using the default client.

func Put

func Put(url string, cfg ...Config) (*Response, error)

Put sends a PUT request using the default client.

func (*Response) Body

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

Body returns the HTTP response body as a byte slice.

func (*Response) CBOR

func (r *Response) CBOR(v any) error

CBOR unmarshals the response body into the given interface{} using CBOR.

func (*Response) Close

func (r *Response) Close()

Close releases both the Request and Response objects back to their pools. After calling Close, do not use these objects.

func (*Response) Cookies

func (r *Response) Cookies() []*fasthttp.Cookie

Cookies returns all cookies set by the response.

The returned values are valid only until the response object is released. Do not store references to returned values; make copies instead.

func (*Response) Header

func (r *Response) Header(key string) string

Header returns the value of the specified response header field.

func (*Response) Headers

func (r *Response) Headers() iter.Seq2[string, []string]

Headers returns all headers in the response using an iterator. Use maps.Collect() to gather them into a map if needed.

The returned values are valid only until the response object is released. Do not store references to returned values; make copies instead.

func (*Response) JSON

func (r *Response) JSON(v any) error

JSON unmarshals the response body into the given interface{} using JSON.

func (*Response) Protocol

func (r *Response) Protocol() string

Protocol returns the HTTP protocol used for the request.

func (*Response) Reset

func (r *Response) Reset()

Reset clears the Response object, making it ready for reuse.

func (*Response) Save

func (r *Response) Save(v any) error

Save writes the response body to a file or io.Writer. If a string path is provided, it creates directories if needed, then writes to a file. If an io.Writer is provided, it writes directly to it.

func (*Response) Status

func (r *Response) Status() string

Status returns the HTTP status message of the executed request.

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns the HTTP status code of the executed request.

func (*Response) String

func (r *Response) String() string

String returns the response body as a trimmed string.

func (*Response) XML

func (r *Response) XML(v any) error

XML unmarshals the response body into the given interface{} using XML.

type ResponseHook

type ResponseHook func(*Client, *Response, *Request) error

ResponseHook is a function invoked after a response is received. It receives a Client, Response, and Request, allowing you to modify the Response data or perform actions based on the response.

type RetryConfig

type RetryConfig = retry.Config

RetryConfig is an alias for the `retry.Config` type from the `addon/retry` package.

type SetFileFunc

type SetFileFunc func(f *File)

SetFileFunc defines a function that modifies a File object.

func SetFileFieldName

func SetFileFieldName(p string) SetFileFunc

SetFileFieldName sets the file's field name.

func SetFileName

func SetFileName(n string) SetFileFunc

SetFileName sets the file name.

func SetFilePath

func SetFilePath(p string) SetFileFunc

SetFilePath sets the file path.

func SetFileReader

func SetFileReader(r io.ReadCloser) SetFileFunc

SetFileReader sets the file's reader.

type WithStruct

type WithStruct interface {
	Add(name, obj string)
	Del(name string)
}

WithStruct is implemented by types that allow data to be stored from a struct via reflection.

Jump to

Keyboard shortcuts

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