Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultParseError(request *Request, response *Response) (any, error)
- func DefaultParseResponse(request *Request, response *Response) (any, error)
- func NewIpv4Transport(transports ...*http.Transport) *http.Transport
- func NewIpv6Transport(transports ...*http.Transport) *http.Transport
- type Client
- func (c *Client) Execute(request *Request) (*Response, error)
- func (c *Client) ExecuteWithContext(ctx context.Context, request *Request) (*Response, error)
- func (c *Client) SetContentType(contentType string)
- func (c *Client) SetEntryPoint(entryPoint string)
- func (c *Client) SetHeader(header, value string)
- func (c *Client) SetHeaders(headers map[string]string)
- func (c *Client) SetMaxRedirects(maximum int)
- func (c *Client) SetMaxResponseSize(size int64)
- func (c *Client) SetParseError(parseError ParseResponse)
- func (c *Client) SetParseResponse(parseResponse ParseResponse)
- func (c *Client) SetRedirectPolicy(policy RedirectPolicy)
- func (c *Client) SetRetryCount(count int)
- func (c *Client) SetRetryMaxWaitTime(wait time.Duration)
- func (c *Client) SetRetryWaitTime(wait time.Duration)
- func (c *Client) SetTimeout(timeout time.Duration)
- func (c *Client) SetTransport(transport *http.Transport)
- func (c *Client) UseMiddleware(middleware ...Middleware)
- type ClientMiddleware
- type FileUpload
- type HTTPClient
- type HandlerFunc
- type Middleware
- type Option
- func WithContentType(contentType string) Option
- func WithHeader(header, value string) Option
- func WithHeaders(headers map[string]string) Option
- func WithMTLS(caCertFile, certFile, keyFile string) Option
- func WithMaxRedirects(maximum int) Option
- func WithMaxResponseSize(size int64) Option
- func WithOnlyIPv4() Option
- func WithOnlyIPv6() Option
- func WithParseError(parseError ParseResponse) Option
- func WithParseResponse(parseResponse ParseResponse) Option
- func WithProxy(proxyURL, user, password string) Option
- func WithRedirectPolicy(policy RedirectPolicy) Option
- func WithRetryCount(count int) Option
- func WithRetryMaxWaitTime(wait time.Duration) Option
- func WithRetryWaitTime(wait time.Duration) Option
- func WithTLSConfig(config *tls.Config) Option
- func WithTimeout(timeout time.Duration) Option
- func WithTransportPool(maxIdleConnsPerHost int, maxIdleConns int, maxConnsPerHost int, ...) Option
- type ParseResponse
- type RedirectConfig
- type RedirectPolicy
- type Request
- func (r *Request) AddQueryParam(param, value string) *Request
- func (r *Request) Clone() *Request
- func (r *Request) GetCreatedAt() time.Time
- func (r *Request) GetErrorRespType() any
- func (r *Request) GetResponseType() any
- func (r *Request) Method() string
- func (r *Request) SetAuthScheme(scheme string) *Request
- func (r *Request) SetAuthToken(authToken string) *Request
- func (r *Request) SetBody(body any) *Request
- func (r *Request) SetContentType(ct string) *Request
- func (r *Request) SetCookie(hc *http.Cookie) *Request
- func (r *Request) SetCookies(rs []*http.Cookie) *Request
- func (r *Request) SetErrorRespType(responseType any) *Request
- func (r *Request) SetFile(fieldName, filePath string) *Request
- func (r *Request) SetFileReader(fieldName, fileName string, reader io.Reader) *Request
- func (r *Request) SetFormData(data map[string]string) *Request
- func (r *Request) SetFormURLEncoded(data map[string]string) *Request
- func (r *Request) SetHeader(header, value string) *Request
- func (r *Request) SetHeaders(headers map[string]string) *Request
- func (r *Request) SetMethod(m string) *Request
- func (r *Request) SetQueryParam(param, value string) *Request
- func (r *Request) SetQueryParams(params map[string]string) *Request
- func (r *Request) SetQueryParamsFromValues(params _url.Values) *Request
- func (r *Request) SetResponseType(responseType any) *Request
- func (r *Request) SetTimeout(timeout time.Duration) *Request
- func (r *Request) SetURL(url string) *Request
- func (r *Request) String() string
- func (r *Request) URL() string
- type Response
- func (r *Response) Bytes() []byte
- func (r *Response) Content() any
- func (r *Response) ContentType() string
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Header() http.Header
- func (r *Response) IsError() bool
- func (r *Response) Proto() string
- func (r *Response) ReceivedAt() time.Time
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- func (r *Response) String() string
Constants ¶
const ( // DefaultTimeout is the default timeout for HTTP requests. DefaultTimeout = 12 * time.Second // DefaultWaitTime is the default wait time between retries. DefaultWaitTime = time.Duration(100) * time.Millisecond // DefaultMaxWaitTime is the maximum wait time between retries. DefaultMaxWaitTime = time.Duration(2000) * time.Millisecond // DefaultUserAgent is the default "User-Agent" value. DefaultUserAgent = "restc/1.0" )
const ( // Application types. TypeApplicationAtomXML = "application/atom+xml" TypeApplicationCBOR = "application/cbor" TypeApplicationEDI = "application/EDI-X12" TypeApplicationEDIFACT = "application/EDIFACT" TypeApplicationFormURLEncoded = "application/x-www-form-urlencoded" TypeApplicationGeoJSON = "application/geo+json" TypeApplicationGZIP = "application/gzip" TypeApplicationHALJSON = "application/hal+json" TypeApplicationJSON = "application/json" TypeApplicationJSONPatch = "application/json-patch+json" TypeApplicationJSONProblem = "application/problem+json" TypeApplicationJavascript = "application/javascript" TypeApplicationLDJSON = "application/ld+json" TypeApplicationMSAccess = "application/msaccess" TypeApplicationMSWord = "application/msword" TypeApplicationMsgPack = "application/msgpack" TypeApplicationNDJSON = "application/x-ndjson" TypeApplicationOctetStream = "application/octet-stream" TypeApplicationOGG = "application/ogg" TypeApplicationOpenXMLSheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" TypeApplicationOpenXMLPresentation = "application/vnd.openxmlformats-officedocument.presentationml.presentation" TypeApplicationOpenXMLWord = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" TypeApplicationPDF = "application/pdf" TypeApplicationProtobuf = "application/x-protobuf" TypeApplicationRAR = "application/vnd.rar" TypeApplicationRTF = "application/rtf" TypeApplicationSVGXML = "application/svg+xml" TypeApplicationTAR = "application/x-tar" TypeApplicationTypescript = "application/typescript" TypeApplicationWASM = "application/wasm" TypeApplicationXHTML = "application/xhtml+xml" TypeApplicationXML = "application/xml" TypeApplicationXMLDTD = "application/xml-dtd" TypeApplicationXMLProblem = "application/problem+xml" TypeApplicationYAML = "application/x-yaml" TypeApplicationZIP = "application/zip" TypeApplication7ZIP = "application/x-7z-compressed" // Multipart types. TypeMultipartAlternative = "multipart/alternative" TypeMultipartFormData = "multipart/form-data" TypeMultipartMixed = "multipart/mixed" TypeMultipartRelated = "multipart/related" // Text types. TypeTextCalendar = "text/calendar" TypeTextCSS = "text/css" TypeTextCSV = "text/csv" TypeTextHTML = "text/html" TypeTextJavascript = "text/javascript" TypeTextMarkdown = "text/markdown" TypeTextPLAIN = "text/plain" TypeTextVCard = "text/vcard" TypeTextXML = "text/xml" TypeTextYAML = "text/yaml" // Image types. TypeImageAPNG = "image/apng" TypeImageAVIF = "image/avif" TypeImageBMP = "image/bmp" TypeImageGIF = "image/gif" TypeImageICO = "image/x-icon" TypeImageJPG = "image/jpeg" TypeImagePNG = "image/png" TypeImageSVGXML = "image/svg+xml" TypeImageTIFF = "image/tiff" TypeImageWEBP = "image/webp" // Video types. TypeVideoAVI = "video/x-msvideo" TypeVideoFLV = "video/x-flv" TypeVideoM3U8 = "application/x-mpegURL" TypeVideoMP4 = "video/mp4" TypeVideoMPEG = "video/mpeg" TypeVideoOGG = "video/ogg" TypeVideoQUICKTIME = "video/quicktime" TypeVideoTS = "video/MP2T" TypeVideoWEBM = "video/webm" TypeVideoWMV = "video/x-ms-wmv" // Audio types. TypeAudioAAC = "audio/aac" TypeAudioFLAC = "audio/flac" TypeAudioMIDI = "audio/midi" TypeAudioMP3 = "audio/mpeg" TypeAudioMP4 = "audio/mp4" TypeAudioOGG = "audio/ogg" TypeAudioOPUS = "audio/opus" TypeAudioWAV = "audio/x-wav" TypeAudioWEBM = "audio/webm" TypeAudioWMV = "audio/x-ms-wma" // Font types. TypeFontOTF = "font/otf" TypeFontTTF = "font/ttf" TypeFontWOFF = "font/woff" TypeFontWOFF2 = "font/woff2" )
Content type constants for various MIME types.
const ( // Accept is the media types that are acceptable. Accept = "Accept" // AcceptCharset is the character sets that are acceptable. AcceptCharset = "Accept-Charset" // AcceptEncoding is the encodings that are acceptable. AcceptEncoding = "Accept-Encoding" // AcceptLanguage is the natural languages that are acceptable. AcceptLanguage = "Accept-Language" // AcceptDatetime is the acceptable datetime. AcceptDatetime = "Accept-Datetime" // Authorization is the credentials for authenticating the user agent. Authorization = "Authorization" // CacheControl is the cache control directives. CacheControl = "Cache-Control" // Connection controls whether the network connection stays open. Connection = "Connection" // ContentLength is the size of the request body in bytes. ContentLength = "Content-Length" // ContentMD5 is the MD5 checksum of the request body. ContentMD5 = "Content-MD5" // ContentType is the media type of the request body. ContentType = "Content-Type" // Cookie contains stored cookies. Cookie = "Cookie" // Date is the date and time at which the message was sent. Date = "Date" // DoNotTrack is the user's tracking preference. DoNotTrack = "DNT" // Expect indicates expectations that need to be fulfilled. Expect = "Expect" // Forwarded provides information about the original request. Forwarded = "Forwarded" // From is the email address of the user. From = "From" // Host specifies the host and port of the server. Host = "Host" // IfMatch is the entity tag. IfMatch = "If-Match" // IfModifiedSince is the modification date constraint. IfModifiedSince = "If-Modified-Since" // IfNoneMatch is the entity tag condition. IfNoneMatch = "If-None-Match" // IfRange is the byte range request. IfRange = "If-Range" // IfUnmodifiedSince is the modification date constraint. IfUnmodifiedSince = "If-Unmodified-Since" // MaxForwards limits the number of proxies or gateways. MaxForwards = "Max-Forwards" // Origin indicates the origin of the request. Origin = "Origin" // Pragma is the implementation-specific directives. Pragma = "Pragma" // ProxyAuthorization contains credentials for the proxy. ProxyAuthorization = "Proxy-Authorization" // Range indicates the byte range to be sent. Range = "Range" // Referer is the address of the previous web page. Referer = "Referer" // TE indicates the transfer encodings the client is willing to accept. TE = "TE" // Trailer indicates that the header provides additional fields. Trailer = "Trailer" // TransferEncoding is the form of encoding used to transfer the payload. TransferEncoding = "Transfer-Encoding" // UserAgent contains information about the user agent. UserAgent = "User-Agent" // Via indicates intermediate proxies or gateways. Via = "Via" // Warning contains warnings about the request. Warning = "Warning" // AcceptPatch is the patch content types the server supports. AcceptPatch = "Accept-Patch" // AcceptRanges indicates unit types the server supports. AcceptRanges = "Accept-Ranges" // Age is the time the object was in a proxy cache. Age = "Age" // Allow lists the methods allowed for the requested URL. Allow = "Allow" // AltSvc is the alternative services. AltSvc = "Alt-Svc" // ContentDisposition indicates if content is inline or attachment. ContentDisposition = "Content-Disposition" // ContentEncoding is the encoding transformations applied. ContentEncoding = "Content-Encoding" // ContentLanguage describes the language(s) of the payload. ContentLanguage = "Content-Language" // ContentLocation indicates the location of the resource. ContentLocation = "Content-Location" // ContentRange indicates where in the full payload the partial content applies. ContentRange = "Content-Range" // ETag is the identifier for a specific version of a resource. ETag = "ETag" // Expires is the date/time after which the response is stale. Expires = "Expires" // LastModified is the date/time the resource was last modified. LastModified = "Last-Modified" // Link provides references to other resources. Link = "Link" // Location is used in redirection or when a resource has been created. Location = "Location" // P3P is the platform for privacy preferences. P3P = "P3P" // ProxyAuthenticate is the authentication method for the proxy. ProxyAuthenticate = "Proxy-Authenticate" // Refresh is automatically refresh the page. Refresh = "Refresh" // RetryAfter indicates the client should wait before retrying the request. RetryAfter = "Retry-After" // Server provides information about the server software. Server = "Server" // SetCookie contains cookies to be sent back to the server. SetCookie = "Set-Cookie" // StrictTransportSecurity forces secure communication. StrictTransportSecurity = "Strict-Transport-Security" // Upgrade is the protocol to switch to. Upgrade = "Upgrade" // Vary indicates the fields that vary in the response. Vary = "Vary" // WWWAuthenticate is the authentication method for the resource. WWWAuthenticate = "WWW-Authenticate" // AccessControlAllowCredentials indicates if credentials can be exposed. AccessControlAllowCredentials = "Access-Control-Allow-Credentials" // AccessControlAllowHeaders indicates which headers can be used. AccessControlAllowHeaders = "Access-Control-Allow-Headers" // AccessControlAllowMethods indicates which methods can be used. AccessControlAllowMethods = "Access-Control-Allow-Methods" // AccessControlAllowOrigin indicates if the resource can be accessed. AccessControlAllowOrigin = "Access-Control-Allow-Origin" // AccessControlExposeHeaders indicates which headers can be exposed. AccessControlExposeHeaders = "Access-Control-Expose-Headers" // AccessControlMaxAge indicates how long the preflight can be cached. AccessControlMaxAge = "Access-Control-Max-Age" // AccessControlRequestHeaders indicates which headers can be used. AccessControlRequestHeaders = "Access-Control-Request-Headers" // AccessControlRequestMethod indicates which method can be used. AccessControlRequestMethod = "Access-Control-Request-Method" // ClearSiteData is the clearance of browser data. ClearSiteData = "Clear-Site-Data" // ContentSecurityPolicy restricts where resources can be loaded from. ContentSecurityPolicy = "Content-Security-Policy" // ContentSecurityPolicyReportOnly restricts where resources can be loaded from. ContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" // CrossOriginEmbedderPolicy controls embedding of cross-origin resources. CrossOriginEmbedderPolicy = "Cross-Origin-Embedder-Policy" // CrossOriginOpenerPolicy controls access to the browsing context. CrossOriginOpenerPolicy = "Cross-Origin-Opener-Policy" // CrossOriginResourcePolicy controls access to the resource. CrossOriginResourcePolicy = "Cross-Origin-Resource-Policy" // NEL is the network error logging. NEL = "NEL" // PermissionsPolicy controls which features can be used. PermissionsPolicy = "Permissions-Policy" // ReferrerPolicy indicates which referrer to send. ReferrerPolicy = "Referrer-Policy" // ReportTo is the reporting endpoints. ReportTo = "Report-To" // TimingAllowOrigin indicates which origins can see timing data. TimingAllowOrigin = "Timing-Allow-Origin" // SecCHUA is the client hints user agent architecture. SecCHUA = "Sec-CH-UA" // SecCHUAMobile is the client hints user agent mobile. SecCHUAMobile = "Sec-CH-UA-Mobile" // SecCHUAPlatform is the client hints user agent platform. SecCHUAPlatform = "Sec-CH-UA-Platform" // SecFetchDest is the fetch destination. SecFetchDest = "Sec-Fetch-Dest" // SecFetchMode is the fetch mode. SecFetchMode = "Sec-Fetch-Mode" // SecFetchSite is the fetch site. SecFetchSite = "Sec-Fetch-Site" // SecFetchUser is the fetch user preference. SecFetchUser = "Sec-Fetch-User" // SecGPC is the global privacy control flag. SecGPC = "Sec-GPC" // SaveData is the save data preference. SaveData = "Save-Data" // UpgradeInsecureRequests is the upgrade insecure requests preference. UpgradeInsecureRequests = "Upgrade-Insecure-Requests" // XAspNetVersion is the ASP.NET version. XAspNetVersion = "X-AspNet-Version" // XAspNetMvcVersion is the ASP.NET MVC version. XAspNetMvcVersion = "X-AspNetMvc-Version" // XContentSecurityPolicy is the content security policy. XContentSecurityPolicy = "X-Content-Security-Policy" // XContentTypeOptions prevents sniffing the content type. XContentTypeOptions = "X-Content-Type-Options" // XCSRFToken is the CSRF token. XCSRFToken = "X-CSRF-Token" //nolint:gosec // XCorrelationId is the correlation ID. XCorrelationId = "X-Correlation-Id" // XDNSPrefetchControl controls DNS prefetching. XDNSPrefetchControl = "X-DNS-Prefetch-Control" // XDownloadOptions indicates how to handle the download. XDownloadOptions = "X-Download-Options" // XForwardedFor is the original client IP address. XForwardedFor = "X-Forwarded-For" // XForwardedProto is the original protocol. XForwardedProto = "X-Forwarded-Proto" // XFrameOptions protects against clickjacking. XFrameOptions = "X-Frame-Options" // XHTTPMethodOverride overrides the HTTP method. XHTTPMethodOverride = "X-HTTP-Method-Override" // XPermittedCrossDomainPolicies controls cross-domain requests. XPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" // XPoweredBy indicates the technology supporting the server. XPoweredBy = "X-Powered-By" // XRealIP is the real client IP address. XRealIP = "X-Real-IP" // XRequestedWith is the XMLHttpRequest header. XRequestedWith = "X-Requested-With" // XRequestId is the request ID. XRequestId = "X-Request-Id" // XRobotsTag controls indexing by robots. XRobotsTag = "X-Robots-Tag" // XRatelimitLimit is the rate limit maximum requests. XRatelimitLimit = "X-Ratelimit-Limit" // XRatelimitRemaining is the rate limit remaining requests. XRatelimitRemaining = "X-Ratelimit-Remaining" // XRatelimitReset is the rate limit reset time. XRatelimitReset = "X-Ratelimit-Reset" // XTraceId is the trace ID. XTraceId = "X-Trace-Id" // XUACompatible indicates the user agent compatibility. XUACompatible = "X-UA-Compatible" // XXSSProtection is the XSS filter. XXSSProtection = "X-XSS-Protection" )
Standard HTTP header constants.
const ( // MethodGet HTTP method. MethodGet = "GET" // MethodPost HTTP method. MethodPost = "POST" // MethodPut HTTP method. MethodPut = "PUT" // MethodDelete HTTP method. MethodDelete = "DELETE" // MethodPatch HTTP method. MethodPatch = "PATCH" // MethodHead HTTP method. MethodHead = "HEAD" // MethodOptions HTTP method. MethodOptions = "OPTIONS" // MethodTrace HTTP method. MethodTrace = "TRACE" )
HTTP method constants.
Variables ¶
var ( // ErrMaxRedirects is returned when the maximum number of redirects is exceeded. ErrMaxRedirects = errors.New("maximum redirects exceeded") // ErrHTTPRequest is returned when an HTTP request fails. ErrHTTPRequest = errors.New("failed to execute HTTP request") // ErrReadBody is returned when reading the response body fails. ErrReadBody = errors.New("failed to read body response") // ErrParseJSON is returned when parsing a JSON response fails. ErrParseJSON = errors.New("failed to parse JSON response") // ErrParseXML is returned when parsing an XML response fails. ErrParseXML = errors.New("failed to parse XML response") // ErrParseHTML is returned when parsing an HTML response fails. ErrParseHTML = errors.New("failed to parse HTML response") // ErrUnexpectedType is returned when the response content type is not supported. ErrUnexpectedType = errors.New("unexpected response type") )
Client errors.
var ( // ErrInvalidMethod is returned when an invalid HTTP method is used. ErrInvalidMethod = errors.New("invalid HTTP method") // ErrUnsupportedScheme is returned when an unsupported URL scheme is used. ErrUnsupportedScheme = errors.New("unsupported URL scheme") // ErrUnsupportedBody is returned when an unsupported body type is used. ErrUnsupportedBody = errors.New("unsupported body type") // ErrInvalidEntryPoint is returned when the entry point URL is invalid. ErrInvalidEntryPoint = errors.New("failed to parse given entry point") // ErrBuildRequest is returned when building the HTTP request fails. ErrBuildRequest = errors.New("failed to build HTTP request") // ErrMultipart is returned when a multipart form error occurs. ErrMultipart = errors.New("multipart form error") )
Request errors.
Functions ¶
func DefaultParseError ¶
DefaultParseError is the default function for parsing error responses (4xx, 5xx). It supports JSON, XML, and HTML content types.
func DefaultParseResponse ¶
DefaultParseResponse is the default function for parsing successful responses. It supports JSON and XML content types.
func NewIpv4Transport ¶ added in v1.5.0
NewIpv4Transport creates an http.Transport that uses only IPv4 connections.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client for making REST API requests. It provides methods for configuring and executing HTTP requests.
func New ¶
New creates a new Client with the given entry point URL and options. The entry point is used as the base URL for relative paths in requests.
func NewWithClient ¶
func NewWithClient(entryPoint string, httpClient HTTPClient, opts ...Option) *Client
NewWithClient creates a new Client with the given entry point URL, custom HTTP client, and options. This allows using a custom http.Client configuration.
func (*Client) Execute ¶
Execute sends the HTTP request and returns the response. It uses context.Background() for the request context.
func (*Client) ExecuteWithContext ¶
ExecuteWithContext sends the HTTP request with the given context and returns the response.
func (*Client) SetContentType ¶ added in v1.5.2
SetContentType sets the default Content-Type header for all requests.
func (*Client) SetEntryPoint ¶
SetEntryPoint sets the base URL for requests.
func (*Client) SetHeaders ¶
SetHeaders sets multiple default headers to be sent with all requests.
func (*Client) SetMaxRedirects ¶
SetMaxRedirects sets the maximum number of redirects to follow.
func (*Client) SetMaxResponseSize ¶
SetMaxResponseSize sets the maximum response body size in bytes. If the response body exceeds this size, it will be truncated.
func (*Client) SetParseError ¶
func (c *Client) SetParseError(parseError ParseResponse)
SetParseError sets the function to parse error responses.
func (*Client) SetParseResponse ¶
func (c *Client) SetParseResponse(parseResponse ParseResponse)
SetParseResponse sets the function to parse successful responses.
func (*Client) SetRedirectPolicy ¶
func (c *Client) SetRedirectPolicy(policy RedirectPolicy)
SetRedirectPolicy sets the redirect policy (FollowRedirects or NoRedirect).
func (*Client) SetRetryCount ¶
SetRetryCount sets the number of retries on failure.
func (*Client) SetRetryMaxWaitTime ¶
SetRetryMaxWaitTime sets the maximum wait time between retries.
func (*Client) SetRetryWaitTime ¶
SetRetryWaitTime sets the wait time between retries.
func (*Client) SetTimeout ¶
SetTimeout sets the timeout for HTTP requests.
func (*Client) SetTransport ¶ added in v1.5.2
SetTransport sets the transport layer for the client.
func (*Client) UseMiddleware ¶
func (c *Client) UseMiddleware(middleware ...Middleware)
UseMiddleware adds middleware to be executed before each request.
type ClientMiddleware ¶
type ClientMiddleware struct {
// contains filtered or unexported fields
}
ClientMiddleware manages a chain of middleware to be executed for each request.
func NewClientMiddleware ¶
func NewClientMiddleware() *ClientMiddleware
NewClientMiddleware creates a new empty ClientMiddleware.
func (*ClientMiddleware) Execute ¶
func (cm *ClientMiddleware) Execute(req *Request, next HandlerFunc) (*Response, error)
Execute runs the middleware chain with the given request and final handler.
func (*ClientMiddleware) Use ¶
func (cm *ClientMiddleware) Use(middleware ...Middleware)
Use adds middleware to the middleware chain.
type FileUpload ¶
FileUpload represents a file to be uploaded in a multipart request.
type HTTPClient ¶
HTTPClient interface represents an HTTP client capable of executing requests.
type HandlerFunc ¶
HandlerFunc is a function that handles an HTTP request and returns a response or error.
type Middleware ¶
type Middleware func(req *Request, next HandlerFunc) (*Response, error)
Middleware is a function that intercepts the request/response flow. It can modify the request before passing it to the next handler, or modify the response after receiving it.
type Option ¶ added in v1.5.0
type Option func(*Client)
Option is a function that configures a Client. It is used with New or NewWithClient to configure the client.
func WithContentType ¶ added in v1.5.2
WithContentType sets the default Content-Type header for all requests.
func WithHeader ¶ added in v1.5.0
WithHeader sets a default header to be sent with all requests.
func WithHeaders ¶ added in v1.5.0
WithHeaders sets multiple default headers to be sent with all requests.
func WithMTLS ¶ added in v1.5.1
WithMTLS configures the mutual TLS authentication with preserving the actual transport layer.
func WithMaxRedirects ¶ added in v1.5.0
WithMaxRedirects sets the maximum number of redirects to follow.
func WithMaxResponseSize ¶ added in v1.5.0
WithMaxResponseSize sets the maximum response body size in bytes.
func WithOnlyIPv4 ¶ added in v1.5.1
func WithOnlyIPv4() Option
WithOnlyIPv4 configures the client to use only IPv4.
func WithOnlyIPv6 ¶ added in v1.5.0
func WithOnlyIPv6() Option
WithOnlyIPv6 configures the client to use only IPv6.
func WithParseError ¶ added in v1.5.0
func WithParseError(parseError ParseResponse) Option
WithParseError sets the function to parse error responses.
func WithParseResponse ¶ added in v1.5.0
func WithParseResponse(parseResponse ParseResponse) Option
WithParseResponse sets the function to parse successful responses.
func WithProxy ¶ added in v1.5.1
WithProxy configures the client to use the specified HTTP proxy. If user and password are provided, basic auth is added to the proxy URL.
func WithRedirectPolicy ¶ added in v1.5.0
func WithRedirectPolicy(policy RedirectPolicy) Option
WithRedirectPolicy sets the redirect policy.
func WithRetryCount ¶ added in v1.5.0
WithRetryCount sets the number of retries on failure.
func WithRetryMaxWaitTime ¶ added in v1.5.0
WithRetryMaxWaitTime sets the maximum wait time between retries.
func WithRetryWaitTime ¶ added in v1.5.0
WithRetryWaitTime sets the initial wait time between retries.
func WithTLSConfig ¶ added in v1.5.1
WithTLSConfig accepts a complete TLS configuration with preserving the actual transport layer.
func WithTimeout ¶ added in v1.5.0
WithTimeout sets the timeout for HTTP requests.
func WithTransportPool ¶ added in v1.5.1
func WithTransportPool( maxIdleConnsPerHost int, maxIdleConns int, maxConnsPerHost int, idleConnTimeout time.Duration, ) Option
WithTransportPool configures the HTTP transport connection pool settings. maxIdleConnsPerHost: max idle connections per host (default: 2) maxIdleConns: total max idle connections (default: 100) maxConnsPerHost: max connections per host, 0 = unlimited idleConnTimeout: how long idle connections stay in the pool.
type ParseResponse ¶
ParseResponse is a function that parses an HTTP response into a custom type.
type RedirectConfig ¶
type RedirectConfig struct {
// contains filtered or unexported fields
}
RedirectConfig holds configuration for redirect handling.
type RedirectPolicy ¶
type RedirectPolicy int
RedirectPolicy defines the behavior for handling HTTP redirects.
const ( // FollowRedirects indicates that the client should follow redirects. FollowRedirects RedirectPolicy = iota // NoRedirect indicates that the client should not follow redirects. NoRedirect )
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request represents an HTTP request with method, URL, headers, body, and other options. It uses a fluent API with method chaining for configuration.
func NewRequest ¶
NewRequest creates a new Request with the given HTTP method and URL.
func (*Request) AddQueryParam ¶
AddQueryParam adds a query parameter to the request URL. Multiple values can be added for the same parameter. Returns the Request for method chaining.
func (*Request) Clone ¶
Clone creates a deep copy of the request. Note: FileUpload Readers are shared between the original and the clone because io.Reader cannot be duplicated. Consuming the reader on one request will affect the other.
func (*Request) GetCreatedAt ¶ added in v1.5.1
GetCreatedAt returns the date and time of the creation.
func (*Request) GetErrorRespType ¶
GetErrorRespType returns the type for unmarshaling error responses.
func (*Request) GetResponseType ¶
GetResponseType returns the type for unmarshaling successful responses.
func (*Request) SetAuthScheme ¶
SetAuthScheme sets the authentication scheme (e.g., "Bearer", "Basic"). Returns the Request for method chaining.
func (*Request) SetAuthToken ¶
SetAuthToken sets the authentication token for the request. The token will be sent in the Authorization header using the specified auth scheme. Returns the Request for method chaining.
func (*Request) SetBody ¶
SetBody sets the request body. Supports string, []byte, io.Reader, or any value that can be JSON marshaled. Returns the Request for method chaining.
func (*Request) SetContentType ¶
SetContentType sets the Content-Type header of the request. Returns the Request for method chaining.
func (*Request) SetCookie ¶
SetCookie adds a cookie to the request. Returns the Request for method chaining.
func (*Request) SetCookies ¶
SetCookies adds multiple cookies to the request. Returns the Request for method chaining.
func (*Request) SetErrorRespType ¶
SetErrorRespType sets the type to unmarshal error responses into. Returns the Request for method chaining.
func (*Request) SetFile ¶
SetFile adds a file from a file path to the multipart form. fieldName is the form field name and filePath is the path to the file. Returns the Request for method chaining.
func (*Request) SetFileReader ¶
SetFileReader adds a file from an io.Reader to the multipart form. fieldName is the form field name and fileName is the file name. Returns the Request for method chaining.
func (*Request) SetFormData ¶
SetFormData sets form data fields for multipart form submission. Returns the Request for method chaining.
func (*Request) SetFormURLEncoded ¶
SetFormURLEncoded sets the body as URL-encoded form data. Returns the Request for method chaining.
func (*Request) SetHeader ¶
SetHeader sets a header for the request. Returns the Request for method chaining.
func (*Request) SetHeaders ¶
SetHeaders sets multiple headers for the request. Returns the Request for method chaining.
func (*Request) SetMethod ¶
SetMethod sets the HTTP method of the request. Returns the Request for method chaining.
func (*Request) SetQueryParam ¶
SetQueryParam sets a query parameter, replacing any existing value. Returns the Request for method chaining.
func (*Request) SetQueryParams ¶
SetQueryParams sets multiple query parameters. Returns the Request for method chaining.
func (*Request) SetQueryParamsFromValues ¶
SetQueryParamsFromValues sets query parameters from url.Values. Returns the Request for method chaining.
func (*Request) SetResponseType ¶
SetResponseType sets the type to unmarshal successful responses into. Returns the Request for method chaining.
func (*Request) SetTimeout ¶
SetTimeout sets a timeout for this specific request. Returns the Request for method chaining.
func (*Request) SetURL ¶
SetURL sets the URL of the request. Returns the Request for method chaining.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response represents an HTTP response with status, headers, and body. It wraps the standard library http.Response and provides additional functionality.
func NewResponse ¶
NewResponse creates a new Response from an http.Response.
func (*Response) Content ¶
Content returns the parsed response content. Content is available after successful parsing with DefaultParseResponse.
func (*Response) ContentType ¶
ContentType returns the Content-Type header value.
func (*Response) ReceivedAt ¶
ReceivedAt returns the time when the response was received.
func (*Response) StatusCode ¶
StatusCode returns the HTTP status code (e.g., 200, 404).