types

package
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 3 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package types provides shared type definitions used across the httpc library. This package eliminates interface duplication between public and internal layers, enabling compile-time type checking without runtime type assertions.

Package types provides shared type definitions used across the httpc library. This package eliminates interface duplication between public and internal layers, enabling compile-time type checking without runtime type assertions.

Index

Constants

View Source
const DefaultUserAgent = "httpc/1.0"

DefaultUserAgent is the value httpc's Defaults.UserAgent carries when the caller does not override it. It lives here — the one internal package both the facade (DefaultConfig) and the fingerprint adapter (which must recognize the engine-side default to drop it in favor of the browser preset's UA) already import — so the two can never drift: a changed literal in one place only would silently stop the fingerprint path from dropping the old default.

Variables

This section is empty.

Functions

This section is empty.

Types

type FileData

type FileData struct {
	// Filename is the name of the file as sent to the server.
	Filename string
	// Content is the raw file content.
	Content []byte
	// ContentType is the MIME type of the file (e.g., "image/png", "application/pdf").
	ContentType string
}

FileData represents a file to be uploaded in a multipart form. It contains the filename, file content, and content type.

type FormData

type FormData struct {
	// Fields contains the text form fields.
	Fields map[string]string
	// Files contains the file uploads mapped by field name.
	Files map[string]*FileData
}

FormData represents multipart form data for HTTP requests. It contains both text fields and file uploads.

Example:

form := &types.FormData{
    Fields: map[string]string{
        "username": "john",
        "email": "john@example.com",
    },
    Files: map[string]*types.FileData{
        "avatar": {
            Filename:    "avatar.png",
            Content:     imageData,
            ContentType: "image/png",
        },
    },
}
client.Post("/upload", httpc.WithFormData(form))

type Handler

type Handler func(ctx context.Context, req RequestMutator) (ResponseMutator, error)

Handler processes an HTTP request and returns a response. This is the core function signature for request processing in the middleware chain.

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

MiddlewareFunc wraps a Handler with additional functionality. Middleware can inspect/modify requests, handle responses, add logging, etc.

type NoTimeoutSetter added in v1.7.0

type NoTimeoutSetter interface {
	SetNoTimeout(v bool)
}

NoTimeoutSetter suppresses the client-level request timeout for one request.

type PrivateIPSetter added in v1.7.0

type PrivateIPSetter interface {
	SetAllowPrivateIPs(v *bool)
}

The narrow capability interfaces below let the httpc facade reach request fields that are intentionally NOT on the public RequestMutator surface: per-request SSRF/retry/no-timeout overrides, the lazy query-param initializer, and the engine's pre/post callbacks. They mirror the sanitizedURLer pattern in package httpc: the facade asserts one of these small contracts instead of downcasting to a concrete engine type, so a third-party RequestMutator implementation degrades gracefully (no-op or a clear error) rather than panicking. The engine's request type satisfies each one by construction, so no engine change is required for these.

These are separate interfaces rather than extra methods on RequestWriter: RequestWriter is public and intended for external implementation, and adding methods to it would be a breaking change for every external implementor.

type QueryParamsEnsurer added in v1.7.0

type QueryParamsEnsurer interface {
	EnsureQueryParams() map[string]any
}

QueryParamsEnsurer lazily initializes and returns the request's query-param map. It backs WithQuery/WithQueryMap, which mutate the returned map in place.

type RequestCallbackSetter added in v1.7.0

type RequestCallbackSetter interface {
	OnRequestMutator() func(RequestMutator) error
	SetOnRequestMutator(cb func(RequestMutator) error)
	OnResponseMutator() func(ResponseMutator) error
	SetOnResponseMutator(cb func(ResponseMutator) error)
}

RequestCallbackSetter reads and installs the engine's pre-request and post-response callbacks. The callback signatures use the public mutator interfaces (not concrete engine types) so this contract stays in the leaf types package and never imports the engine. The *Mutator method names avoid colliding with the engine's concrete OnRequest/SetOnRequest accessors, whose signatures carry the concrete request type.

type RequestMutator

type RequestMutator interface {
	RequestReader
	RequestWriter
}

RequestMutator provides read-write access to request data for middleware and request options. It embeds RequestReader and RequestWriter for full access to request properties. Middleware can inspect and modify request properties before the request is sent.

LIFETIME CONTRACT: the maps returned by Headers() and QueryParams() are pooled internal storage, valid only for the duration of the request. Do not retain references beyond the middleware call (e.g. in async logging or audit pipelines) — after the request completes the maps are cleared and recycled for unrelated requests. Copy the data if you need to keep it.

OWNERSHIP CONTRACT (setter side): SetHeaders and SetQueryParams COPY the supplied maps into engine-owned pooled storage. Passing a caller-owned or shared map is safe — the engine never retains the argument, and later mutations to it do not affect the in-flight request.

type RequestReader

type RequestReader interface {
	Method() string
	URL() string
	Headers() map[string]string
	QueryParams() map[string]any
	Body() any
	Timeout() time.Duration
	MaxRetries() int
	Context() context.Context
	Cookies() []http.Cookie
	FollowRedirects() *bool
	MaxRedirects() *int
	StreamBody() bool
}

RequestReader provides read-only access to request data. Use it when a consumer only inspects request properties without modifying them (mirroring how ResponseReader is used by RetryPolicy).

type RequestWriter

type RequestWriter interface {
	SetMethod(string)
	SetURL(string)
	SetHeaders(map[string]string)
	SetHeader(key, value string)
	SetQueryParams(map[string]any)
	SetBody(any)
	SetTimeout(time.Duration)
	SetMaxRetries(int)
	SetContext(context.Context)
	SetCookies([]http.Cookie)
	SetFollowRedirects(*bool)
	SetMaxRedirects(*int)
	SetStreamBody(bool)
}

RequestWriter provides write-only access to request data. Use it when a consumer only modifies request properties without reading them.

type ResponseMutator

type ResponseMutator interface {
	ResponseReader
	ResponseWriter
}

ResponseMutator provides read-write access to response data for middleware. It embeds ResponseReader and ResponseWriter for full access to response properties. Middleware can inspect and modify response properties after the request completes. This is useful for:

  • Response caching middleware
  • Response transformation (e.g., JSON pretty-printing)
  • Content encoding/decoding
  • Response filtering

type ResponseReader

type ResponseReader interface {
	StatusCode() int
	Status() string
	Proto() string
	Headers() http.Header
	Body() string
	RawBody() []byte
	ContentLength() int64
	Duration() time.Duration
	Attempts() int
	Cookies() []*http.Cookie
	RedirectChain() []string
	RedirectCount() int
	RequestHeaders() http.Header
	RequestURL() string
	RequestMethod() string
}

ResponseReader provides read-only access to response data for middleware. Use this interface when middleware only needs to inspect response properties without modifying them. It is also the interface consumed by RetryPolicy.

type ResponseWriter

type ResponseWriter interface {
	SetStatusCode(int)
	SetStatus(string)
	SetProto(string)
	SetHeaders(http.Header)
	SetBody(string)
	SetRawBody([]byte)
	SetContentLength(int64)
	SetDuration(time.Duration)
	SetAttempts(int)
	SetCookies([]*http.Cookie)
	SetRedirectChain([]string)
	SetRedirectCount(int)
	SetRequestHeaders(http.Header)
	SetRequestURL(string)
	SetRequestMethod(string)
	SetHeader(key string, values ...string)
}

ResponseWriter provides write-only access to response data. Use it when a consumer only modifies response properties without reading them.

Note on SetHeader: the key is stored exactly as given — it is NOT canonicalized (unlike the request-side SetHeader). Writing "content-type" alongside a server-sent canonical "Content-Type" yields two distinct entries; pass http.CanonicalMIMEHeaderKey spelling to replace an existing header.

type RetryNonIdempotentSetter added in v1.7.0

type RetryNonIdempotentSetter interface {
	SetRetryNonIdempotent(v *bool)
}

RetryNonIdempotentSetter sets the per-request non-idempotent retry override.

type RetryPolicy

type RetryPolicy interface {
	// ShouldRetry determines if a request should be retried based on the
	// response, error, and current attempt number (0-indexed).
	// Return true to retry, false to stop.
	ShouldRetry(resp ResponseReader, err error, attempt int) bool

	// GetDelay returns the delay duration before the next retry attempt.
	GetDelay(attempt int) time.Duration

	// MaxRetries returns the maximum number of retry attempts.
	MaxRetries() int
}

RetryPolicy defines the interface for custom retry behavior. Implementations can provide custom retry strategies beyond the default exponential backoff with jitter.

Example implementation:

type CustomRetryPolicy struct {
    maxRetries int
}

func (p *CustomRetryPolicy) ShouldRetry(resp ResponseReader, err error, attempt int) bool {
    if err != nil {
        return true // Retry on errors
    }
    if resp.StatusCode() >= 500 && resp.StatusCode() < 600 {
        return attempt < p.maxRetries
    }
    return false
}

func (p *CustomRetryPolicy) GetDelay(attempt int) time.Duration {
    return time.Second * time.Duration(attempt+1)
}

func (p *CustomRetryPolicy) MaxRetries() int {
    return p.maxRetries
}

Jump to

Keyboard shortcuts

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