Documentation
¶
Overview ¶
Package fetch provides a flexible and composable HTTP client with middleware support.
Index ¶
- type Dispatcher
- func (d *Dispatcher) Client() *http.Client
- func (d *Dispatcher) Clone() *Dispatcher
- func (d *Dispatcher) CoreMiddlewares() []Middleware
- func (d *Dispatcher) Dispatch(req *http.Request, middlewares ...Middleware) (*http.Response, error)
- func (d *Dispatcher) Middlewares() []Middleware
- func (d *Dispatcher) NewRequest(middlewares ...Middleware) *Request
- func (d *Dispatcher) R(middlewares ...Middleware) *Request
- func (d *Dispatcher) SetClient(client *http.Client)
- func (d *Dispatcher) SetCoreMiddlewares(middlewares ...Middleware)
- func (d *Dispatcher) SetMiddlewares(middlewares ...Middleware)
- func (d *Dispatcher) Use(middlewares ...Middleware)
- func (d *Dispatcher) UseCore(middlewares ...Middleware)
- type Handler
- type HandlerFunc
- type Middleware
- func AddCookie(cookies ...*http.Cookie) Middleware
- func AddHeaderFromMap(headers map[string]string) Middleware
- func AddHeaderKV(key, value string) Middleware
- func AddQueryFromMap(params map[string]string) Middleware
- func AddQueryKV(key, value string) Middleware
- func DelAllCookies() Middleware
- func DelHeader(keys ...string) Middleware
- func DelQuery(keys ...string) Middleware
- func SetBaseURL(uri string) Middleware
- func SetBody(reader io.Reader) Middleware
- func SetBodyForm(data url.Values) Middleware
- func SetBodyGet(getReader func() (io.Reader, error)) Middleware
- func SetBodyGetBytes(getBytes func() ([]byte, error)) Middleware
- func SetBodyJSON(data any) Middleware
- func SetBodyXML(data any) Middleware
- func SetContentType(contentType string) Middleware
- func SetHeader(funcs ...func(h http.Header)) Middleware
- func SetHeaderFromMap(headers map[string]string) Middleware
- func SetHeaderKV(key, value string) Middleware
- func SetMultipart(fields []*MultipartField, opts ...func(*MultipartOptions)) Middleware
- func SetPathParams(params map[string]string) Middleware
- func SetPathPrefix(prefix string) Middleware
- func SetPathSuffix(suffix string) Middleware
- func SetQuery(funcs ...func(query url.Values)) Middleware
- func SetQueryFromMap(params map[string]string) Middleware
- func SetQueryKV(key, value string) Middleware
- func SetUserAgent(userAgent string) Middleware
- func Skip() Middleware
- type MultipartField
- type MultipartFieldCallbackFunc
- type MultipartFieldProgress
- type MultipartOptions
- type Request
- func (r *Request) AddCookie(cookie ...*http.Cookie) *Request
- func (r *Request) AddHeaderFromMap(headers map[string]string) *Request
- func (r *Request) AddHeaderKV(key, value string) *Request
- func (r *Request) AddQueryFromMap(params map[string]string) *Request
- func (r *Request) AddQueryKV(key, value string) *Request
- func (r *Request) BaseURL(baseURL string) *Request
- func (r *Request) Body(reader io.Reader) *Request
- func (r *Request) BodyGet(get func() (io.Reader, error)) *Request
- func (r *Request) BodyGetBytes(get func() ([]byte, error)) *Request
- func (r *Request) Clone() *Request
- func (r *Request) ContentType(contentType string) *Request
- func (r *Request) DelAllCookies() *Request
- func (r *Request) DelHeader(keys ...string) *Request
- func (r *Request) DelQuery(keys ...string) *Request
- func (r *Request) Delete(url string) *Response
- func (r *Request) DeleteContext(ctx context.Context, url string) *Response
- func (r *Request) Do(req *http.Request) (*http.Response, error)
- func (r *Request) Form(form url.Values) *Request
- func (r *Request) Get(url string) *Response
- func (r *Request) GetContext(ctx context.Context, url string) *Response
- func (r *Request) Head(url string) *Response
- func (r *Request) HeadContext(ctx context.Context, url string) *Response
- func (r *Request) Header(funcs ...func(http.Header)) *Request
- func (r *Request) HeaderFromMap(headers map[string]string) *Request
- func (r *Request) HeaderKV(key, value string) *Request
- func (r *Request) JSON(data any) *Request
- func (r *Request) Multipart(fields []*MultipartField, opts ...func(*MultipartOptions)) *Request
- func (r *Request) Options(url string) *Response
- func (r *Request) OptionsContext(ctx context.Context, url string) *Response
- func (r *Request) Patch(url string) *Response
- func (r *Request) PatchContext(ctx context.Context, url string) *Response
- func (r *Request) PathParams(params map[string]string) *Request
- func (r *Request) PathPrefix(prefix string) *Request
- func (r *Request) PathSuffix(suffix string) *Request
- func (r *Request) Post(url string) *Response
- func (r *Request) PostContext(ctx context.Context, url string) *Response
- func (r *Request) Put(url string) *Response
- func (r *Request) PutContext(ctx context.Context, url string) *Response
- func (r *Request) Query(funcs ...func(url.Values)) *Request
- func (r *Request) Send(method string, u string) *Response
- func (r *Request) SendContext(ctx context.Context, method string, u string) *Response
- func (r *Request) SetQueryFromMap(params map[string]string) *Request
- func (r *Request) SetQueryKV(key, value string) *Request
- func (r *Request) Trace(url string) *Response
- func (r *Request) TraceContext(ctx context.Context, url string) *Response
- func (r *Request) Use(middlewares ...Middleware) *Request
- func (r *Request) UserAgent(userAgent string) *Request
- func (r *Request) XML(data any) *Request
- type Response
- func (r *Response) Bytes() []byte
- func (r *Response) ClearInternalBuffer()
- func (r *Response) Close() error
- func (r *Response) JSON(userStruct any) error
- func (r *Response) Read(p []byte) (n int, err error)
- func (r *Response) SaveToFile(fileName string) error
- func (r *Response) String() string
- func (r *Response) XML(userStruct any) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher manages HTTP client operations with middleware support. It wraps an http.Client and applies middleware chains to requests. All methods are safe for concurrent use.
func NewDispatcher ¶
func NewDispatcher(client *http.Client, middlewares ...Middleware) *Dispatcher
NewDispatcher creates a new Dispatcher with the given HTTP client and middleware. If client is nil, a default client is created with no timeout.
func NewDispatcherWithTransport ¶
func NewDispatcherWithTransport(transport http.RoundTripper, middlewares ...Middleware) *Dispatcher
NewDispatcherWithTransport creates a new Dispatcher with a custom RoundTripper transport. A default http.Client with no timeout is created using the provided transport.
func (*Dispatcher) Client ¶
func (d *Dispatcher) Client() *http.Client
Client returns the underlying HTTP client.
func (*Dispatcher) Clone ¶
func (d *Dispatcher) Clone() *Dispatcher
Clone creates a shallow copy of the Dispatcher. The HTTP client is cloned, and middlewares are copied.
func (*Dispatcher) CoreMiddlewares ¶
func (d *Dispatcher) CoreMiddlewares() []Middleware
CoreMiddlewares returns the dispatcher's core middlewares.
func (*Dispatcher) Dispatch ¶
func (d *Dispatcher) Dispatch(req *http.Request, middlewares ...Middleware) (*http.Response, error)
Dispatch executes the HTTP request with the dispatcher's middleware chain. Middleware execution order (outermost to innermost):
- d.middlewares (dispatcher's middleware)
- middlewares (per-request middleware)
- d.coreMiddlewares (core middleware, applied last)
func (*Dispatcher) Middlewares ¶
func (d *Dispatcher) Middlewares() []Middleware
Middlewares returns the current middleware chain.
func (*Dispatcher) NewRequest ¶
func (d *Dispatcher) NewRequest(middlewares ...Middleware) *Request
NewRequest creates a new Request bound to this dispatcher.
func (*Dispatcher) R ¶
func (d *Dispatcher) R(middlewares ...Middleware) *Request
R is an alias for NewRequest, creating a new Request bound to this dispatcher.
func (*Dispatcher) SetClient ¶
func (d *Dispatcher) SetClient(client *http.Client)
SetClient replaces the underlying HTTP client. This operation is safe for concurrent use. If client is nil, the method does nothing.
func (*Dispatcher) SetCoreMiddlewares ¶
func (d *Dispatcher) SetCoreMiddlewares(middlewares ...Middleware)
SetCoreMiddlewares replaces the dispatcher's core middlewares.
func (*Dispatcher) SetMiddlewares ¶
func (d *Dispatcher) SetMiddlewares(middlewares ...Middleware)
SetMiddlewares replaces the current middleware chain.
func (*Dispatcher) Use ¶
func (d *Dispatcher) Use(middlewares ...Middleware)
Use appends middleware to the dispatcher's middleware chain. Note: This modifies the dispatcher in place. If you need an immutable copy, use Clone() first.
func (*Dispatcher) UseCore ¶
func (d *Dispatcher) UseCore(middlewares ...Middleware)
UseCore appends middleware to the dispatcher's core middleware chain. Core middlewares are applied last (innermost layer) in the middleware chain. Note: This modifies the dispatcher in place.
type Handler ¶
Handler executes HTTP requests. Receives both client and request to enable middleware to modify or replace the client if needed.
type HandlerFunc ¶
HandlerFunc adapts functions to Handler interface.
type Middleware ¶
Middleware wraps Handler to add cross-cutting concerns. Can short-circuit the chain or delegate to next handler.
func AddCookie ¶
func AddCookie(cookies ...*http.Cookie) Middleware
AddCookie adds one or more HTTP cookies to the request. Multiple cookies with the same name will all be sent.
func AddHeaderFromMap ¶
func AddHeaderFromMap(headers map[string]string) Middleware
AddHeaderFromMap adds multiple headers from a map. Preserves existing values.
func AddHeaderKV ¶
func AddHeaderKV(key, value string) Middleware
AddHeaderKV adds a header value. Preserves existing values for the same key.
func AddQueryFromMap ¶
func AddQueryFromMap(params map[string]string) Middleware
AddQueryFromMap adds multiple query parameters from a map. Preserves existing values.
func AddQueryKV ¶
func AddQueryKV(key, value string) Middleware
AddQueryKV adds a query parameter. Preserves existing values for the same key.
func DelAllCookies ¶
func DelAllCookies() Middleware
DelAllCookies removes all cookies from the request by deleting the Cookie header.
func SetBaseURL ¶
func SetBaseURL(uri string) Middleware
SetBaseURL returns a middleware that sets the base URL (scheme and host) for the request. If the URI doesn't include a scheme (http:// or https://), it defaults to http://.
This is useful for targeting different environments (dev, staging, prod) or when the base URL needs to be determined dynamically.
Example:
// Both will set the base URL to http://api.example.com
fetch.SetBaseURL("http://api.example.com")
fetch.SetBaseURL("api.example.com")
func SetBody ¶
func SetBody(reader io.Reader) Middleware
SetBody sets the request body from an io.Reader. Note: The reader is consumed and cannot be retried. Use SetBodyGet for retry support.
func SetBodyForm ¶
func SetBodyForm(data url.Values) Middleware
SetBodyForm encodes form data as the request body. Sets Content-Type to application/x-www-form-urlencoded.
func SetBodyGet ¶
func SetBodyGet(getReader func() (io.Reader, error)) Middleware
SetBodyGet lazily provides the request body via a getter function. The getter is called on each request attempt, enabling retry support.
func SetBodyGetBytes ¶
func SetBodyGetBytes(getBytes func() ([]byte, error)) Middleware
SetBodyGetBytes lazily provides the request body as bytes, supporting retries.
func SetBodyJSON ¶
func SetBodyJSON(data any) Middleware
SetBodyJSON marshals data to JSON as the request body. Sets Content-Type to application/json.
func SetBodyXML ¶
func SetBodyXML(data any) Middleware
SetBodyXML marshals data to XML as the request body. Sets Content-Type to application/xml.
func SetContentType ¶
func SetContentType(contentType string) Middleware
SetContentType sets the Content-Type header.
func SetHeader ¶
func SetHeader(funcs ...func(h http.Header)) Middleware
SetHeader applies functions to modify request headers. Functions execute in order. Use this for complex header logic beyond simple key-value pairs.
func SetHeaderFromMap ¶
func SetHeaderFromMap(headers map[string]string) Middleware
SetHeaderFromMap sets multiple headers from a map. Replaces existing values.
func SetHeaderKV ¶
func SetHeaderKV(key, value string) Middleware
SetHeaderKV sets a header value. Replaces existing values for the same key.
func SetMultipart ¶
func SetMultipart(fields []*MultipartField, opts ...func(*MultipartOptions)) Middleware
SetMultipart builds multipart/form-data requests. Streams fields through a pipe to avoid memory overhead. Supports progress tracking.
func SetPathParams ¶
func SetPathParams(params map[string]string) Middleware
SetPathParams returns a middleware that replaces path parameter placeholders with actual values. Placeholders should be in the format {key}, and they will be replaced with the corresponding value from the params map.
This is useful for RESTful APIs with path parameters like /users/{id}/posts/{postId}.
Example:
// Request URL: /users/{id}/posts/{postId}
// After SetPathParams(map[string]string{"id": "123", "postId": "456"})
// Result: /users/123/posts/456
func SetPathPrefix ¶
func SetPathPrefix(prefix string) Middleware
SetPathPrefix returns a middleware that prepends a path segment to the request URL's path. This is useful for adding API base paths or namespace prefixes.
Example:
// Request URL: /users
// After SetPathPrefix("/api/v1"): /api/v1/users
func SetPathSuffix ¶
func SetPathSuffix(suffix string) Middleware
SetPathSuffix returns a middleware that appends a path segment to the request URL's path. This is useful for adding API versions or resource identifiers to the end of a path.
Example:
// Request URL: /api/users
// After SetPathSuffix("/123"): /api/users/123
func SetQuery ¶
func SetQuery(funcs ...func(query url.Values)) Middleware
SetQuery applies functions to modify URL query parameters. Functions execute in order. Use this for complex query logic beyond simple key-value pairs.
func SetQueryFromMap ¶
func SetQueryFromMap(params map[string]string) Middleware
SetQueryFromMap sets multiple query parameters from a map. Replaces existing values.
func SetQueryKV ¶
func SetQueryKV(key, value string) Middleware
SetQueryKV sets a query parameter. Replaces existing values for the same key.
func SetUserAgent ¶
func SetUserAgent(userAgent string) Middleware
SetUserAgent sets the User-Agent header.
func Skip ¶
func Skip() Middleware
Skip returns a no-op middleware that passes requests through unchanged.
type MultipartField ¶
type MultipartField struct {
Name string
FileName string
ContentType string
GetReader func() (io.ReadCloser, error)
FileSize int64
ExtraContentDisposition map[string]string
ProgressInterval time.Duration
ProgressCallback MultipartFieldCallbackFunc
Values []string
}
MultipartField represents a multipart/form-data field. Supports both simple form values and file uploads with optional progress tracking.
type MultipartFieldCallbackFunc ¶
type MultipartFieldCallbackFunc func(MultipartFieldProgress)
MultipartFieldCallbackFunc receives progress updates during upload.
type MultipartFieldProgress ¶
MultipartFieldProgress reports upload progress for a field.
type MultipartOptions ¶
type MultipartOptions struct {
Boundary string
}
MultipartOptions configures multipart request creation.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request represents an HTTP request builder that can accumulate middleware before being executed. It maintains a reference to its parent Dispatcher and builds up a middleware chain.
func (*Request) AddCookie ¶
AddCookie appends one or more cookies to the request. Use this when you need to send authentication tokens or session data.
func (*Request) AddHeaderFromMap ¶
AddHeaderFromMap appends multiple headers from a map without replacing existing values. Use this when you have a set of headers to add in batch.
func (*Request) AddHeaderKV ¶
AddHeaderKV appends a header value to the request without replacing existing values. Use this when a header can have multiple values (e.g., Accept, Cookie).
func (*Request) AddQueryFromMap ¶
AddQueryFromMap appends multiple query parameters from a map without replacing existing values. Use this when you have a set of parameters to add in batch.
func (*Request) AddQueryKV ¶
AddQueryKV appends a query parameter without replacing existing values. Use this when a parameter can have multiple values (e.g., ?tag=a&tag=b).
func (*Request) BaseURL ¶
BaseURL sets the base URL (scheme and host) for the request. Use this to target different environments or when the base URL is dynamic.
func (*Request) Body ¶
Body sets the request body from an io.Reader. Options can configure Content-Type and automatic Content-Length.
func (*Request) BodyGet ¶
BodyGet sets the request body using a lazy getter function. The function is called when the body is actually needed.
func (*Request) BodyGetBytes ¶
BodyGetBytes sets the request body using a lazy getter function that returns bytes. The function is called when the body is actually needed.
func (*Request) Clone ¶
Clone creates a shallow copy of the Request. The dispatcher reference is preserved, and middleware are copied.
func (*Request) ContentType ¶
ContentType sets the Content-Type header. Most body methods (JSON, XML, Form) set this automatically.
func (*Request) DelAllCookies ¶
DelAllCookies removes all cookies from the request. Use this when you need to ensure no cookies are sent with the request.
func (*Request) DelHeader ¶
DelHeader removes one or more headers from the request. Use this when you need to prevent certain headers from being sent.
func (*Request) DelQuery ¶
DelQuery removes one or more query parameters from the request. Use this when you need to prevent certain parameters from being sent.
func (*Request) Delete ¶
Delete method does DELETE HTTP request. It's defined in section 9.3.5 of RFC 9110.
func (*Request) DeleteContext ¶
DeleteContext performs a DELETE request with the given context. Use the context to control timeouts and cancellation.
func (*Request) Form ¶
Form sets the request body as URL-encoded form data. Automatically sets Content-Type to application/x-www-form-urlencoded.
func (*Request) GetContext ¶
GetContext performs a GET request with the given context. Use the context to control timeouts and cancellation.
func (*Request) Head ¶
Head method does HEAD HTTP request. It's defined in section 9.3.2 of RFC 9110.
func (*Request) HeadContext ¶
HeadContext performs a HEAD request with the given context. Use the context to control timeouts and cancellation.
func (*Request) Header ¶
Header applies one or more functions to modify the request headers. Use this for complex header manipulation that requires custom logic.
func (*Request) HeaderFromMap ¶
HeaderFromMap sets multiple headers from a map, replacing existing values. Use this when you want to reset headers to a known state.
func (*Request) HeaderKV ¶
HeaderKV sets a single header value, replacing any existing values. Use this when you want to ensure only one value for a header (e.g., Content-Type).
func (*Request) JSON ¶
JSON sets the request body as JSON-encoded data. Accepts string, []byte, or any type that can be marshaled to JSON. Automatically sets Content-Type to application/json.
func (*Request) Multipart ¶
func (r *Request) Multipart(fields []*MultipartField, opts ...func(*MultipartOptions)) *Request
Multipart creates a multipart/form-data request body with the given fields.
func (*Request) Options ¶
Options method does OPTIONS HTTP request. It's defined in section 9.3.7 of RFC 9110.
func (*Request) OptionsContext ¶
OptionsContext performs an OPTIONS request with the given context. Use the context to control timeouts and cancellation.
func (*Request) Patch ¶
Patch method does PATCH HTTP request. It's defined in section 2 of RFC 5789.
func (*Request) PatchContext ¶
PatchContext performs a PATCH request with the given context. Use the context to control timeouts and cancellation.
func (*Request) PathParams ¶
PathParams replaces path parameter placeholders with actual values. Use this for RESTful APIs with path parameters (e.g., /users/{id} → /users/123).
func (*Request) PathPrefix ¶
PathPrefix prepends a path segment to the request URL's path. Use this to add API base paths (e.g., /users → /api/v1/users).
func (*Request) PathSuffix ¶
PathSuffix appends a path segment to the request URL's path. Use this to add resource identifiers (e.g., /users → /users/123).
func (*Request) Post ¶
Post method does POST HTTP request. It's defined in section 9.3.3 of RFC 9110.
func (*Request) PostContext ¶
PostContext performs a POST request with the given context. Use the context to control timeouts and cancellation.
func (*Request) PutContext ¶
PutContext performs a PUT request with the given context. Use the context to control timeouts and cancellation.
func (*Request) Query ¶
Query applies one or more functions to modify the request query parameters. Use this for complex query manipulation that requires custom logic.
func (*Request) Send ¶
Send constructs and executes an HTTP request with the given method and URL. Returns a Response which wraps the http.Response or any error.
func (*Request) SendContext ¶
func (*Request) SetQueryFromMap ¶
SetQueryFromMap sets multiple query parameters from a map, replacing existing values. Use this when you want to reset query parameters to a known state.
func (*Request) SetQueryKV ¶
SetQueryKV sets a single query parameter, replacing any existing values. Use this when you want to ensure only one value for a parameter.
func (*Request) Trace ¶
Trace method does TRACE HTTP request. It's defined in section 9.3.8 of RFC 9110.
func (*Request) TraceContext ¶
TraceContext performs a TRACE request with the given context. Use the context to control timeouts and cancellation.
func (*Request) Use ¶
func (r *Request) Use(middlewares ...Middleware) *Request
Use appends middleware to this request's middleware chain. Returns the request for method chaining.
type Response ¶
type Response struct {
Error error
Header http.Header
Cookies []*http.Cookie
RawRequest *http.Request
RawResponse *http.Response
// contains filtered or unexported fields
}
Response wraps an HTTP response and provides convenient methods for reading and decoding the response body. It implements io.Reader and buffers content for multiple reads.
func (*Response) Bytes ¶
Bytes returns the response body as a byte slice. Uses internal buffering for efficient multiple reads.
func (*Response) ClearInternalBuffer ¶
func (r *Response) ClearInternalBuffer()
ClearInternalBuffer resets the internal buffer. Does nothing if an error is present.
func (*Response) Close ¶
Close discards any remaining response body and closes it. Safe to call even when Error is present or RawResponse is nil.
func (*Response) Read ¶
Read implements io.Reader by reading from the underlying response body. Returns an error if the response contains an error.
func (*Response) SaveToFile ¶
SaveToFile writes the response body to a file. Uses internal buffering if available.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
bufferpool
Package bufferpool provides a buffer pool for bytes.Buffer instances.
|
Package bufferpool provides a buffer pool for bytes.Buffer instances. |
|
pool
Package pool provides internal pool utilities.
|
Package pool provides internal pool utilities. |