options

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package options provides configuration types for the HTTP client.

Option Configuration

Option is the main configuration type, created with New:

opt := options.New().
    AddHeader("Content-Type", "application/json").
    SetCompression(options.CompressionGzip)

Options use embedded config structs for organization:

Compression

Built-in compression types:

Progress Tracking

Track upload and download progress:

opt := options.New()
opt.Progress.OnUpload = func(bytesRead, totalBytes int64) {
    fmt.Printf("Uploaded %d of %d bytes\n", bytesRead, totalBytes)
}

Index

Constants

View Source
const MaxReplayableBodySize = 10 * 1024 * 1024 // 10MB

MaxReplayableBodySize is the maximum size of a non-seekable request body that will be buffered for redirect/retry replay. Bodies larger than this limit that cannot be seeked (like streaming io.Reader) will fail on redirect/retry with ErrPayloadNotReplayable.

Variables

View Source
var (
	ErrInvalidWriterType  = errors.New("invalid writer type")
	ErrMissingFilePath    = errors.New("file path must be specified when using WriteToFile")
	ErrUnexpectedFilePath = errors.New("filepath should not be provided when using WriteToBuffer")
	ErrInvalidCompression = errors.New("unsupported compression type")
	ErrFileNotFound       = errors.New("file does not exist")
	ErrFileNotPrepared    = errors.New("no file prepared: call PrepareFile first")
)

Common errors returned by Option methods

Functions

func NewProgressReader

func NewProgressReader(r io.Reader, totalSize int64, onProgress func(current, total int64)) io.Reader

NewProgressReader returns an io.Reader that reports progress during read operations. If totalSize is <= 0, it attempts to determine size using io.Seeker if available. The onProgress callback receives current bytes read and total size (-1 if unknown).

func NewProgressWriter

func NewProgressWriter(w io.Writer, totalSize int64, onProgress func(current, total int64)) io.Writer

NewProgressWriter returns an io.Writer that tracks progress during write operations. The onProgress callback is invoked with current bytes written and total size. Use for scenarios like download progress tracking.

Types

type CompressionConfig

type CompressionConfig struct {
	// Type specifies the compression algorithm to use.
	Type CompressionType

	// CustomType is the Content-Encoding header value when using custom compression.
	CustomType CompressionType

	// Compressor is a function that returns a custom compressor.
	// Only used when Type is CompressionCustom.
	Compressor func(w *io.PipeWriter) (io.WriteCloser, error)

	// Decompressor is a function that returns a custom decompressor.
	// Used for decompressing responses with custom encoding.
	Decompressor func(r io.Reader) (io.Reader, error)
}

CompressionConfig holds compression-related settings.

type CompressionType

type CompressionType string

CompressionType defines the compression algorithm used for HTTP requests. It supports standard compression types (gzip, deflate, brotli) as well as custom compression implementations.

const (
	CompressionNone    CompressionType = ""        // No compression
	CompressionGzip    CompressionType = "gzip"    // Gzip compression (RFC 1952)
	CompressionDeflate CompressionType = "deflate" // Deflate compression (RFC 1951)
	CompressionBrotli  CompressionType = "br"      // Brotli compression
	CompressionCustom  CompressionType = "custom"  // Custom compression implementation
)

Compression types supported by the client

type FileConfig

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

FileConfig holds file upload metadata.

func (*FileConfig) SetPath

func (f *FileConfig) SetPath(path string)

SetPath sets the file path directly on the FileConfig. This is used internally when an *os.File is passed as payload to enable path-based reopening for redirects.

func (*FileConfig) SetSize

func (f *FileConfig) SetSize(size int64)

SetSize sets the file size directly on the FileConfig.

type LoggingConfig

type LoggingConfig struct {
	// Enabled controls whether verbose logging is active.
	Enabled bool

	// Logger is the slog.Logger instance used for logging.
	Logger slog.Logger
}

LoggingConfig holds logging-related settings.

type Option

type Option struct {
	Context        context.Context   // Optional context for request cancellation and timeouts. If nil, context.Background() is used.
	Logging        LoggingConfig     // Logging configuration
	Header         http.Header       // Headers to be included in the request
	Cookies        []*http.Cookie    // Cookies to be included in the request
	Compression    CompressionConfig // Compression configuration
	UserAgent      string            // User Agent to send with requests
	Redirect       RedirectConfig    // Redirect configuration
	Tracing        TracingConfig     // Request tracing configuration
	Transport      TransportConfig   // Transport and protocol settings
	File           FileConfig        // File upload metadata
	ResponseWriter ResponseWriter    // Define the type of response writer
	Progress       ProgressConfig    // Progress tracking configuration
	Range          RangeConfig       // Range request configuration for partial downloads
	// contains filtered or unexported fields
}

Option provides configuration for HTTP requests. It allows customization of various aspects of the request including headers, compression, logging, response handling, and progress tracking. If no options are provided when making a request, a default configuration is automatically generated.

Options are safe for concurrent use when accessed through their getter/setter methods, which use internal mutex protection. Direct field access should be avoided in concurrent contexts.

func New

func New(opts ...*Option) *Option

New creates a default Option with pre-configured settings. If additional options are provided via the variadic parameter, they will be merged with the default settings, with the provided options taking precedence.

func (*Option) AddCookie

func (opt *Option) AddCookie(cookie *http.Cookie) *Option

AddCookie adds a new cookie to the Option's cookie collection. If the cookie slice hasn't been initialized, it will be created.

func (*Option) AddHeader

func (opt *Option) AddHeader(key string, value string) *Option

AddHeader adds a new header with the specified key and value to the request headers. If the headers map hasn't been initialized, it will be created. Kept for backwards compatability

func (*Option) ClearCookies

func (opt *Option) ClearCookies() *Option

ClearCookies removes all previously set cookies from the Option.

func (*Option) ClearHeaders

func (opt *Option) ClearHeaders() *Option

ClearHeaders removes all previously set headers from the Option.

func (*Option) ClearRange

func (opt *Option) ClearRange() *Option

ClearRange removes any configured range settings.

func (*Option) Client

func (opt *Option) Client() *http.Client

Client returns the HTTP client to be used for requests. If a custom client has been set via SetClient, that client is returned. Otherwise, returns a new default http.Client instance.

func (*Option) Clone

func (opt *Option) Clone() *Option

Clone creates an independent deep copy of the Option.

This method creates a copy of all configuration including:

  • Headers and cookies (deep copied)
  • Logging, compression, redirect, and transport settings
  • Progress callbacks and buffer sizes
  • Range configuration

The returned Option can be modified without affecting the original.

Note: Function references (callbacks) are copied by reference, not cloned. Modifying the underlying function behavior will affect all copies.

func (*Option) CreatePayloadReader

func (opt *Option) CreatePayloadReader(payload any) (io.Reader, int64, error)

CreatePayloadReader converts the given payload into an io.Reader along with its size. Supported payload types include:

  • nil: Returns a nil reader and a size of -1.
  • []byte: Returns a bytes.Reader for the byte slice and its length as size.
  • *bytes.Buffer: Returns a bytes.Reader for the buffer data and its length as size.
  • io.Reader: Returns the reader and attempts to determine its size if it implements io.Seeker.
  • string: Returns a strings.Reader for the string and its length as size.

For unsupported payload types, an error is returned.

func (*Option) DisableLogging

func (opt *Option) DisableLogging() *Option

DisableLogging turns off verbose logging for the Option instance.

func (*Option) DisablePreserveMethod

func (opt *Option) DisablePreserveMethod() *Option

DisablePreserveMethod configures redirects to not maintain the original HTTP method.

func (*Option) DisableRedirects

func (opt *Option) DisableRedirects() *Option

DisableRedirects configures the Option to not follow HTTP redirects.

func (*Option) EnableLogging

func (opt *Option) EnableLogging() *Option

EnableLogging turns on verbose logging for the Option instance.

func (*Option) EnablePreserveMethod

func (opt *Option) EnablePreserveMethod() *Option

EnablePreserveMethod configures redirects to maintain the original HTTP method.

func (*Option) EnableRedirects

func (opt *Option) EnableRedirects() *Option

EnableRedirects configures the Option to follow HTTP redirects.

func (*Option) Filename

func (opt *Option) Filename() string

Filename returns the path of the prepared file. Returns empty string if no file has been prepared.

func (*Option) GenerateIdentifier

func (opt *Option) GenerateIdentifier() string

GenerateIdentifier creates a unique identifier based on the configured Type. Returns a UUID, ULID, or random string, or empty string if no identifier type is configured.

func (*Option) HasFile

func (opt *Option) HasFile() bool

HasFile returns true if a file has been prepared for upload.

func (*Option) HasRange

func (opt *Option) HasRange() bool

HasRange returns true if a range has been configured.

func (*Option) IdentifierType

func (opt *Option) IdentifierType() UniqueIdentifierType

IdentifierType returns the current identifier type setting.

func (*Option) InitialiseWriter

func (opt *Option) InitialiseWriter() (io.WriteCloser, error)

InitialiseWriter sets up the appropriate writer based on the ResponseWriter configuration. Returns an error if the writer type is invalid or if required parameters are missing. When resuming a download (Range.IsResume is true), files are opened in append mode.

func (*Option) Log

func (opt *Option) Log(msg string, args ...any)

Log logs a message if verbose logging is enabled. The message will be logged at INFO level with any additional arguments provided.

func (*Option) MaxRedirects

func (opt *Option) MaxRedirects() int

MaxRedirects returns the maximum number of redirects configured.

func (*Option) Merge

func (opt *Option) Merge(src *Option) *Option

Merge combines the settings from another Option instance into this one. Settings from the source Option take precedence over existing settings. This includes headers, cookies, compression settings, and all other configuration options.

func (*Option) NewCompressor

func (opt *Option) NewCompressor(w *io.PipeWriter) (io.WriteCloser, error)

NewCompressor returns an appropriate io.WriteCloser based on the configured compression type.

func (*Option) NewDecompressor

func (opt *Option) NewDecompressor(r io.ReadCloser, encoding string) (io.ReadCloser, error)

NewDecompressor returns an appropriate io.Reader for the given encoding.

func (*Option) OnDownloadProgress

func (opt *Option) OnDownloadProgress(fn func(bytesRead, totalBytes int64)) *Option

OnDownloadProgress sets a callback function to track download progress.

func (*Option) OnUploadProgress

func (opt *Option) OnUploadProgress(fn func(bytesRead, totalBytes int64)) *Option

OnUploadProgress sets a callback function to track upload progress.

func (*Option) OpenFile

func (opt *Option) OpenFile() (*os.File, error)

OpenFile opens and returns a fresh file handle for the prepared file. This should be called each time a file read is needed (initial request, redirects, retries). The caller is responsible for closing the returned file. Returns an error if no file has been prepared or if opening fails.

func (*Option) PrepareFile

func (opt *Option) PrepareFile(filename string) error

PrepareFile validates a file for upload and stores its metadata. It checks that the file exists and is accessible, stores the filename and size, infers the content type, and sets Content-Disposition headers. The file is NOT opened - use OpenFile() to get a fresh file handle.

func (*Option) ProgressTracking

func (opt *Option) ProgressTracking() ProgressTracking

ProgressTracking returns the current progress tracking setting.

func (*Option) Redirects

func (opt *Option) Redirects(enabled bool, preserve bool, max int) *Option

Redirects configures HTTP redirect behavior. enabled - whether to follow redirects preserve - whether to preserve the original HTTP method on redirect max - maximum number of redirects to follow (defaults to 5 if 0)

func (*Option) Resume

func (opt *Option) Resume(filepath string) *Option

Resume configures the request to resume a download to an existing partial file. It determines the current file size and sets the appropriate Range header to continue downloading from where the previous download stopped. The file output is automatically set to the same path, opened in append mode.

If the file doesn't exist or is empty, the download starts from the beginning.

Example usage:

opt := options.New().Resume("/path/to/partial.bin")
resp, err := client.Get("https://example.com/file.bin", opt)

func (*Option) SetBufferOutput

func (opt *Option) SetBufferOutput() *Option

SetBufferOutput configures the response writer to write responses to an in-memory buffer.

func (*Option) SetClient

func (opt *Option) SetClient(client *http.Client) *Option

SetClient configures a custom HTTP client to be used for requests. This client will be used instead of the default client for all subsequent requests made with this Option instance. The provided client should be configured with any desired settings (timeouts, transport, etc) before being set.

Note: If the provided client has a nil Transport, the library will use http.DefaultTransport as a fallback. Be aware that any modifications to this transport will affect the global default. If you require isolation, ensure your custom client has its own Transport configured.

func (*Option) SetCompression

func (opt *Option) SetCompression(compressionType CompressionType) *Option

SetCompression configures the compression type to be used for the request. Valid compression types include: none, gzip, deflate, brotli, and custom.

func (*Option) SetContext

func (opt *Option) SetContext(ctx context.Context) *Option

SetContext configures an optional context for the request.

The context can be used for:

  • Request cancellation: Cancel in-flight requests when the context is cancelled
  • Timeouts: Set deadlines for request completion using context.WithTimeout()
  • Request-scoped values: Pass values through the request chain

If no context is set (nil), context.Background() is used by default.

Example usage:

// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
opt := options.New().SetContext(ctx)
resp, err := client.Get(url, opt)

// With cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
    <-someSignal
    cancel()
}()
opt := options.New().SetContext(ctx)

This method returns the Option pointer for method chaining.

func (*Option) SetDownloadBufferSize

func (opt *Option) SetDownloadBufferSize(size int) *Option

SetDownloadBufferSize configures the buffer size used when downloading files. The size must be positive; otherwise, the setting will be ignored.

func (*Option) SetFileOutput

func (opt *Option) SetFileOutput(filepath string) *Option

SetFileOutput configures the response writer to write responses to a file at the specified path.

func (*Option) SetIdentifierType

func (opt *Option) SetIdentifierType(t UniqueIdentifierType) *Option

SetIdentifierType configures which identifier type to use for request tracing.

func (*Option) SetLogger

func (opt *Option) SetLogger(logger *slog.Logger) *Option

SetLogger configures a custom logger and enables verbose logging. The provided logger will replace any existing logger configuration.

func (*Option) SetMaxRedirects

func (opt *Option) SetMaxRedirects(max int) *Option

SetMaxRedirects sets the maximum number of redirects to follow.

func (*Option) SetMaxResponseHeaderBytes

func (opt *Option) SetMaxResponseHeaderBytes(size int64) *Option

SetMaxResponseHeaderBytes configures the maximum number of bytes allowed for response headers, including all 1xx informational responses. This is particularly relevant for APIs that send multiple 1xx responses (e.g., 100 Continue, 103 Early Hints). A value of 0 uses Go's default of 1MB.

The value is stored in Option and applied to a cloned transport at request time, ensuring thread-safety and avoiding mutation of shared transport instances.

func (*Option) SetOutput

func (opt *Option) SetOutput(writerType ResponseWriterType, filepath ...string) error

SetOutput configures how the response should be written, either to a file or buffer. For file output, a filepath must be provided. Returns an error if the configuration is invalid.

func (*Option) SetProtocol

func (opt *Option) SetProtocol(p Protocol) *Option

SetProtocol configures which HTTP protocol version(s) to use for requests.

The default is Both, which uses HTTP/1.1 for http:// URLs and negotiates HTTP/2 for https:// URLs via ALPN. This matches Go's standard behaviour.

Protocol selection is applied per-request by cloning the transport, ensuring that protocol settings do not affect other requests or the global default transport.

Example usage:

opt := options.New().SetProtocol(options.HTTP1)  // Force HTTP/1.1
opt := options.New().SetProtocol(options.HTTP2)  // Force HTTP/2 (https:// only)

Important considerations:

  • HTTP2 requires https:// URLs; using it with http:// will result in connection errors.
  • UnencryptedHTTP2 (h2c) requires server support and is typically only used in controlled environments.
  • For advanced HTTP/2 tuning (MaxConcurrentStreams, flow control, ping timeouts), configure a custom Transport via SetTransport() or use client.NewCustom().

This method returns the Option pointer for method chaining.

func (*Option) SetProtocolScheme

func (opt *Option) SetProtocolScheme(scheme string) *Option

SetProtocolScheme sets the protocol scheme (e.g., "http://", "https://") for requests. If the provided scheme doesn't end with "://", it will be automatically appended.

func (*Option) SetRange

func (opt *Option) SetRange(start, end int64) *Option

SetRange configures an explicit byte range for partial content requests. Both start and end are inclusive byte offsets (0-indexed). For example, SetRange(0, 499) requests the first 500 bytes.

func (*Option) SetRangeFrom

func (opt *Option) SetRangeFrom(offset int64) *Option

SetRangeFrom configures a range from the specified byte offset to the end of the resource. For example, SetRangeFrom(1000) requests all bytes from offset 1000 onwards.

func (*Option) SetRangeLast

func (opt *Option) SetRangeLast(n int64) *Option

SetRangeLast configures a range to request the last n bytes of the resource. For example, SetRangeLast(1024) requests the last 1024 bytes.

func (*Option) SetTransport

func (opt *Option) SetTransport(transport *http.Transport) *Option

SetTransport configures a custom HTTP transport for the requests. This allows fine-grained control over connection pooling, timeouts, and other transport-level settings.

func (*Option) SetUploadBufferSize

func (opt *Option) SetUploadBufferSize(size int) *Option

SetUploadBufferSize configures the buffer size used when uploading files. The size must be positive; otherwise, the setting will be ignored.

func (*Option) Size

func (opt *Option) Size() int64

Size returns the size in bytes of the prepared file. Returns 0 if no file has been prepared.

func (*Option) TrackAfterCompression

func (opt *Option) TrackAfterCompression() *Option

TrackAfterCompression sets progress tracking to occur after data compression. This tracks actual transfer size but not original data size.

func (*Option) TrackBeforeCompression

func (opt *Option) TrackBeforeCompression() *Option

TrackBeforeCompression sets progress tracking to occur before data compression. This tracks the original data size but may not reflect final transfer size.

func (*Option) UseJsonLogger

func (opt *Option) UseJsonLogger() *Option

UseJsonLogger configures the Option to use a JSON-based logger and enables verbose logging. The logger will output to stdout using the default slog JSONHandler format.

func (*Option) UsePerRequestClient

func (opt *Option) UsePerRequestClient() *Option

UsePerRequestClient disables the use of the shared HTTP client for this Option instance. This creates a new client for each request, providing better isolation at the cost of performance. Use this when you need complete isolation between requests or when you want to customize client behavior for specific requests without affecting other requests. UsePerRequestClient disables shared client and ensures a new client is created

func (*Option) UseSharedClient

func (opt *Option) UseSharedClient() *Option

UseSharedClient enables the use of the shared HTTP client for this Option instance. Using a shared client provides better performance through connection pooling and reuse, especially when making multiple requests to the same host. This is the default behavior. The shared client is thread-safe and can be used concurrently across multiple goroutines.

func (*Option) UseTextLogger

func (opt *Option) UseTextLogger() *Option

UseTextLogger configures the Option to use a text-based logger and enables verbose logging. The logger will output to stdout using the default slog TextHandler format.

func (*Option) Writer

func (opt *Option) Writer() io.WriteCloser

Writer returns the currently configured io.WriteCloser instance.

type ProgressConfig

type ProgressConfig struct {
	// Tracking determines when progress is measured relative to compression.
	Tracking ProgressTracking

	// OnUpload is called during upload with bytes read and total bytes.
	// Total bytes may be -1 if unknown (e.g., streaming or compressed).
	OnUpload func(bytesRead, totalBytes int64)

	// OnDownload is called during download with bytes read and total bytes.
	// Total bytes may be -1 if unknown (e.g., chunked or compressed).
	OnDownload func(bytesRead, totalBytes int64)

	// UploadBufferSize controls the buffer size when uploading.
	// If nil, default buffer size is used.
	UploadBufferSize *int

	// DownloadBufferSize controls the buffer size when downloading.
	// If nil, default buffer size is used.
	DownloadBufferSize *int
}

ProgressConfig holds progress tracking settings.

type ProgressTracking

type ProgressTracking int

ProgressTracking defines when progress should be tracked relative to compression.

const (
	// TrackBeforeCompression tracks progress on original data before compression.
	// This shows actual data size but may not reflect transfer size.
	TrackBeforeCompression ProgressTracking = iota

	// TrackAfterCompression tracks progress on compressed data during transfer.
	// This shows actual transfer size but not original data size.
	TrackAfterCompression
)

type Protocol

type Protocol int

Protocol defines which HTTP protocol versions to use for requests. This type leverages Go 1.24's Transport.Protocols field to provide explicit control over HTTP version negotiation.

By default, Go's HTTP client uses HTTP/1.1 for unencrypted connections (http://) and negotiates HTTP/2 via ALPN for TLS connections (https://). The Protocol type allows overriding this behaviour for specific use cases.

Note: Changing the protocol affects connection behaviour. HTTP/2 uses multiplexed streams over a single connection, whilst HTTP/1.1 may open multiple connections. Consider connection pooling implications when selecting a protocol.

const (
	// Both uses HTTP/1.1 for http:// URLs and HTTP/2 for https:// URLs.
	// This is the default behaviour and matches Go's standard HTTP client.
	Both Protocol = iota

	// HTTP1 forces HTTP/1.1 for all requests, regardless of URL scheme.
	// Useful for compatibility with servers that have HTTP/2 issues.
	HTTP1

	// HTTP2 forces HTTP/2 for all requests. Requires https:// URLs as HTTP/2
	// depends on TLS for protocol negotiation (ALPN). Requests to http:// URLs
	// will fail when this protocol is selected.
	HTTP2

	// UnencryptedHTTP2 enables HTTP/2 over plaintext TCP (h2c). This is an
	// advanced option for use in controlled environments where TLS is not
	// required. The target server must support HTTP/2 cleartext upgrades.
	UnencryptedHTTP2
)

Protocol constants for HTTP version selection.

Usage considerations:

  • Both: Recommended for most applications. Provides automatic protocol selection based on the URL scheme and server capabilities.
  • HTTP1: Use when targeting servers that have HTTP/2 compatibility issues, or when debugging protocol-specific behaviour.
  • HTTP2: Use when HTTP/2 features (multiplexing, header compression) are required and the target server is known to support HTTP/2. Note: Only works with https:// URLs as HTTP/2 requires TLS for protocol negotiation via ALPN.
  • UnencryptedHTTP2: Use for HTTP/2 over plaintext (h2c), typically in controlled environments such as internal services or behind a TLS-terminating proxy. The server must explicitly support h2c; most public servers do not.

type RangeConfig

type RangeConfig struct {
	// Start is the starting byte offset (inclusive).
	// Used with End for explicit ranges, or alone for "from offset to end".
	Start int64

	// End is the ending byte offset (inclusive).
	// When zero and Start is set, the range extends to the end of the resource.
	End int64

	// Last specifies the number of bytes from the end of the resource.
	// When set, Start and End are ignored, and the range is "last N bytes".
	Last int64

	// IsSet indicates whether a range has been configured.
	IsSet bool

	// IsResume indicates this is a resume operation from an existing partial file.
	// When true, the response writer should open in append mode.
	IsResume bool
}

RangeConfig holds configuration for HTTP Range requests (RFC 7233). This enables partial content downloads and resumable downloads.

func (*RangeConfig) RangeHeader

func (rc *RangeConfig) RangeHeader() string

RangeHeader returns the formatted Range header value for the request. Returns an empty string if no range is configured.

type RedirectConfig

type RedirectConfig struct {
	// Follow determines whether HTTP redirects are automatically followed.
	// When false (default), the redirect response is returned as-is.
	Follow bool

	// PreserveMethod maintains the original HTTP method on redirect.
	// By default (false), redirects switch to GET as per HTTP spec.
	PreserveMethod bool

	// Max is the maximum number of redirects to follow before giving up.
	Max int
}

RedirectConfig holds redirect behaviour settings.

type ResponseWriter

type ResponseWriter struct {
	// Type determines the destination for response data.
	// Must be either WriteToBuffer or WriteToFile.
	Type ResponseWriterType

	// FilePath specifies the destination file path when Type is WriteToFile.
	// This field is ignored when Type is WriteToBuffer.
	// The path must be writable and will be created if it doesn't exist.
	FilePath string
	// contains filtered or unexported fields
}

ResponseWriter contains configuration for handling HTTP response bodies. It supports writing responses either to an in-memory buffer or directly to a file, allowing for flexible response handling based on the needs of the caller.

type ResponseWriterType

type ResponseWriterType string

ResponseWriterType defines how the HTTP response body should be handled. It determines whether responses are written to an in-memory buffer or directly to a file.

const (
	// WriteToBuffer indicates that responses should be written to an in-memory buffer.
	// This is useful for smaller responses that need to be processed in memory.
	WriteToBuffer ResponseWriterType = "buffer"

	// WriteToFile indicates that responses should be written directly to a file.
	// This is recommended for large responses to minimize memory usage.
	WriteToFile ResponseWriterType = "file"
)

Supported response writer types

type TracingConfig

type TracingConfig struct {
	// Type specifies which identifier type to use for request tracing.
	Type UniqueIdentifierType
	// contains filtered or unexported fields
}

TracingConfig holds request tracing configuration.

type TransportConfig

type TransportConfig struct {
	// HTTP is the HTTP transport to use for requests.
	HTTP *http.Transport

	// MaxResponseHeaderBytes limits the size of response headers including 1xx responses.
	// 0 uses Go's default (1MB).
	MaxResponseHeaderBytes int64

	// Protocol specifies HTTP protocol version selection (Both, HTTP1, HTTP2, UnencryptedHTTP2).
	Protocol Protocol

	// Scheme defines the protocol scheme (e.g., "https://", "http://") for requests.
	Scheme string
}

TransportConfig holds transport and protocol settings.

type UniqueIdentifierType

type UniqueIdentifierType string

UniqueIdentifierType defines the type of unique identifier to use for request tracing. It supports both UUID and ULID formats.

const (
	IdentifierNone UniqueIdentifierType = ""     // No identifier
	IdentifierUUID UniqueIdentifierType = "uuid" // UUID v4
	IdentifierULID UniqueIdentifierType = "ulid" // ULID timestamp-based identifier
	IdentifierRGS  UniqueIdentifierType = "rgs"  // Randomly generated string
)

Supported identifier types for request tracing

type WriteCloserBuffer

type WriteCloserBuffer struct {
	*bytes.Buffer
}

WriteCloserBuffer is a wrapper around bytes.Buffer that implements the io.WriteCloser interface. It is used as an in-memory buffer for writing data where closing the buffer does not require any additional cleanup or resource management.

func (*WriteCloserBuffer) Close

func (wcb *WriteCloserBuffer) Close() error

Close satisfies the io.WriteCloser interface but performs no action. This is because there are no resources to release or clean up for an in-memory buffer.

func (*WriteCloserBuffer) IsEmpty

func (w *WriteCloserBuffer) IsEmpty() bool

IsEmpty returns true if the buffer is nil or contains no data. This is used to check if a response body was received before accessing its contents.

Jump to

Keyboard shortcuts

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