Documentation
¶
Index ¶
- Variables
- func NewProgressReader(r io.Reader, totalSize int64, onProgress func(current, total int64)) io.Reader
- func NewProgressWriter(w io.Writer, totalSize int64, onProgress func(current, total int64)) io.Writer
- type CompressionType
- type Option
- func (opt *Option) AddCookie(cookie *http.Cookie) *Option
- func (opt *Option) AddHeader(key string, value string) *Option
- func (opt *Option) CheckRedirects() bool
- func (opt *Option) ClearCookies()
- func (opt *Option) ClearHeaders()
- func (opt *Option) CloseFile() error
- func (opt *Option) CreatePayloadReader(payload any) (io.Reader, int64, error)
- func (opt *Option) DisableLogging()
- func (opt *Option) DisablePreserveMethodOnRedirect() *Option
- func (opt *Option) DisableRedirects() *Option
- func (opt *Option) EnableLogging()
- func (opt *Option) EnablePreserveMethodOnRedirect() *Option
- func (opt *Option) EnableRedirects() *Option
- func (opt *Option) Filesize() int64
- func (opt *Option) GenerateIdentifier() string
- func (opt *Option) GetClient() *http.Client
- func (opt *Option) GetCompressor(w *io.PipeWriter) (io.WriteCloser, error)
- func (opt *Option) GetDecompressor(r io.ReadCloser, encoding string) (io.ReadCloser, error)
- func (opt *Option) GetFile() *os.File
- func (opt *Option) GetMaxRedirects() int
- func (opt *Option) GetProgressTracking() ProgressTracking
- func (opt *Option) GetWriter() io.WriteCloser
- func (opt *Option) HasFileHandle() bool
- func (opt *Option) InferContentType(file *os.File, fileInfo os.FileInfo) error
- func (opt *Option) InitialiseWriter() (io.WriteCloser, error)
- func (opt *Option) Log(msg string, args ...any)
- func (opt *Option) Merge(src *Option)
- func (opt *Option) PrepareFile(filename string) error
- func (opt *Option) Redirects(enabled bool, preserve bool, max int) *Option
- func (opt *Option) ReopenFile() (*os.File, error)
- func (opt *Option) SetBufferOutput()
- func (opt *Option) SetClient(client *http.Client)
- func (opt *Option) SetCompression(compressionType CompressionType) *Option
- func (opt *Option) SetContext(ctx context.Context) *Option
- func (opt *Option) SetDownloadBufferSize(size int)
- func (opt *Option) SetFile(file *os.File) error
- func (opt *Option) SetFileOutput(filepath string)
- func (opt *Option) SetLogger(logger *slog.Logger)
- func (opt *Option) SetMaxRedirects(size int) *Option
- func (opt *Option) SetMaxResponseHeaderBytes(size int64) *Option
- func (opt *Option) SetOutput(writerType ResponseWriterType, filepath ...string) error
- func (opt *Option) SetProgressTracking(pt ProgressTracking) *Option
- func (opt *Option) SetProtocol(p Protocol) *Option
- func (opt *Option) SetProtocolScheme(scheme string)
- func (opt *Option) SetTransport(transport *http.Transport)
- func (opt *Option) SetUploadBufferSize(size int)
- func (opt *Option) TrackAfterCompression() *Option
- func (opt *Option) TrackBeforeCompression() *Option
- func (opt *Option) UseJsonLogger()
- func (opt *Option) UsePerRequestClient()
- func (opt *Option) UseSharedClient()
- func (opt *Option) UseTextLogger()
- type ProgressTracking
- type Protocol
- type ResponseWriter
- type ResponseWriterType
- type UniqueIdentifierType
- type WriteCloserBuffer
Constants ¶
This section is empty.
Variables ¶
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") )
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.
This function wraps an existing io.Reader to monitor bytes as they are read, invoking a callback function with progress updates. It is commonly used for tracking upload progress when sending request bodies.
How It Works ¶
NewProgressReader uses io.TeeReader to create a reader that sends data to two destinations as it is read:
- The original destination (whoever called Read) - gets the actual data
- A progress tracker - which counts bytes and invokes the callback
This approach is transparent to the caller - they receive the same data they would have received from the original reader.
Automatic Size Detection ¶
If totalSize is <= 0 and the reader implements io.Seeker (e.g., *os.File), NewProgressReader automatically determines the size by seeking to the end and back. This allows accurate percentage-based progress for file uploads without requiring the caller to know the file size in advance.
Parameters ¶
- r: The underlying io.Reader to wrap (e.g., a file, buffer, or network stream)
- totalSize: The expected total number of bytes to be read. Pass -1 or 0 if unknown. If the reader is an io.Seeker and totalSize <= 0, the size will be detected automatically.
- onProgress: A callback function invoked after each read with the current byte count and total size. The callback signature is func(current, total int64):
- current: Total bytes read so far (cumulative across all Read calls)
- total: The total size (detected or provided), or -1 if unknown
Use Cases ¶
This function is primarily useful for:
- Tracking upload progress when sending file bodies in HTTP requests
- Monitoring data being read from any io.Reader with progress feedback
- Building custom progress indicators for read operations
Usage Example ¶
file, _ := os.Open("largefile.zip")
defer file.Close()
progressReader := options.NewProgressReader(file, 0, func(current, total int64) {
// totalSize auto-detected from file
fmt.Printf("\rUpload progress: %d/%d bytes", current, total)
})
req, _ := http.NewRequest("POST", url, progressReader)
client.Do(req)
Thread Safety ¶
The returned reader uses atomic operations internally for the byte counter, making it safe if the same reader is somehow used from multiple goroutines. However, io.Reader implementations typically expect sequential reads, so concurrent reads from the same reader are generally not recommended regardless of thread safety.
Relationship to NewProgressWriter ¶
While NewProgressReader tracks bytes as they are read FROM a source, NewProgressWriter tracks bytes as they are written TO a destination. Both use the same underlying progress tracking mechanism and callback signature.
Choose based on where you have control:
- Use NewProgressReader when you control the reading side (e.g., uploading a file)
- Use NewProgressWriter when you control the writing side (e.g., saving a download)
func NewProgressWriter ¶ added in v2.1.0
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.
This function wraps an existing io.Writer to monitor bytes as they are written, invoking a callback function with progress updates. It is the write-side counterpart to NewProgressReader.
How It Works ¶
NewProgressWriter uses io.MultiWriter to create a writer that sends data to two destinations simultaneously:
- The original writer (w) - where data actually goes
- A progress tracker - which counts bytes and invokes the callback
This approach has zero overhead on the write path since io.MultiWriter handles the fan-out efficiently, and the progress tracker's Write method only updates a counter and calls the callback.
Parameters ¶
- w: The underlying io.Writer to wrap (e.g., a file, network connection, or buffer)
- totalSize: The expected total number of bytes to be written. Pass -1 or 0 if the total size is unknown. When unknown, the callback receives -1 as the total parameter, allowing it to display indeterminate progress.
- onProgress: A callback function invoked after each write with the current byte count and total size. The callback signature is func(current, total int64) where:
- current: Total bytes written so far (cumulative across all Write calls)
- total: The totalSize passed to NewProgressWriter, or -1 if unknown
Use Cases ¶
This function is primarily useful for:
- Tracking download progress when writing response bodies to files
- Monitoring data being written to any io.Writer with progress feedback
- Building custom progress indicators for write operations
Usage Example ¶
file, _ := os.Create("output.txt")
defer file.Close()
progressWriter := options.NewProgressWriter(file, contentLength, func(current, total int64) {
if total > 0 {
fmt.Printf("\rProgress: %d/%d bytes (%.1f%%)", current, total, float64(current)/float64(total)*100)
} else {
fmt.Printf("\rWritten: %d bytes", current)
}
})
io.Copy(progressWriter, responseBody)
Thread Safety ¶
The returned writer uses atomic operations internally for the byte counter, making it safe for concurrent writes. However, the callback itself may be invoked from multiple goroutines simultaneously if writes happen concurrently, so the callback implementation should be thread-safe if concurrent writes are expected.
Relationship to NewProgressReader ¶
While NewProgressReader tracks bytes as they are read FROM a source, NewProgressWriter tracks bytes as they are written TO a destination. Both use the same underlying progress tracking mechanism and callback signature.
Choose based on where you have control:
- Use NewProgressReader when you control the reading side (e.g., uploading a file)
- Use NewProgressWriter when you control the writing side (e.g., saving a download)
Types ¶
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 Option ¶
type Option struct {
Context context.Context // Optional context for request cancellation and timeouts. If nil, context.Background() is used.
Verbose bool // Whether logging should be verbose or not
Logger slog.Logger // Logging - default uses the slog TextHandler
Header http.Header // Headers to be included in the request
Cookies []*http.Cookie // Cookies to be included in the request
ProtocolScheme string // define a custom protocol scheme. It defaults to https
Compression CompressionType // CompressionType to use: none, gzip, deflate or brotli
CustomCompressionType CompressionType // When using a custom compression, specify the type to be used as the content-encoding header.
CustomCompressor func(w *io.PipeWriter) (io.WriteCloser, error) // Function for custom compression
CustomDecompressor func(r io.Reader) (io.Reader, error) // Function for custom decompression
UserAgent string // User Agent to send with requests
FollowRedirects bool // When true, HTTP redirects are automatically followed. When false (default), the redirect response is returned as-is.
PreserveMethodOnRedirect bool // Default is false
MaxRedirects int // Maximum number of redirects that can happen before the client gives up
UniqueIdentifierType UniqueIdentifierType // Internal trace or identifier for the request
Transport *http.Transport // Create our own default transport
MaxResponseHeaderBytes int64 // Maximum bytes for response headers including 1xx responses. 0 uses Go's default (1MB).
Protocol Protocol // HTTP protocol version selection (Both, HTTP1, HTTP2, UnencryptedHTTP2). Default is Both.
ResponseWriter ResponseWriter // Define the type of response writer
UploadBufferSize *int // Control the size of the buffer when uploading a file
DownloadBufferSize *int // Control the size of the buffer when downloading a file
OnUploadProgress func(bytesRead, totalBytes int64) // To monitor and track progress when uploading
OnDownloadProgress func(bytesRead, totalBytes int64) // To monitor and track progress when downloading
// 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.
func New ¶
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 ¶
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 ¶
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) CheckRedirects ¶
func (*Option) ClearCookies ¶
func (opt *Option) ClearCookies()
ClearCookies removes all previously set cookies from the Option.
func (*Option) ClearHeaders ¶
func (opt *Option) ClearHeaders()
ClearHeaders removes all previously set headers from the Option.
func (*Option) CloseFile ¶
CloseFile closes the currently open file if one exists and resets related metadata. It logs the closure through the configured logger and returns any error encountered during closing. After closing, the file pointer is set to nil and the filesize is reset to 0.
func (*Option) CreatePayloadReader ¶
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. - 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()
DisableLogging turns off verbose logging for the Option instance.
func (*Option) DisablePreserveMethodOnRedirect ¶
DisablePreserveMethodOnRedirect configures redirects to not maintain the original HTTP method.
func (*Option) DisableRedirects ¶
DisableRedirects configures the Option to not follow HTTP redirects.
func (*Option) EnableLogging ¶
func (opt *Option) EnableLogging()
EnableLogging turns on verbose logging for the Option instance.
func (*Option) EnablePreserveMethodOnRedirect ¶
EnablePreserveMethodOnRedirect configures redirects to maintain the original HTTP method.
func (*Option) EnableRedirects ¶
EnableRedirects configures the Option to follow HTTP redirects.
func (*Option) Filesize ¶
Filesize returns the size in bytes of the currently configured file. Returns 0 if no file is set or if the file size could not be determined. This value is set when the file is initially prepared or set.
func (*Option) GenerateIdentifier ¶
GenerateIdentifier creates a unique identifier based on the configured UniqueIdentifierType. Returns a UUID or ULID string, or an empty string if no identifier type is configured.
func (*Option) GetClient ¶
GetClient 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) GetCompressor ¶
func (opt *Option) GetCompressor(w *io.PipeWriter) (io.WriteCloser, error)
GetCompressor returns an appropriate io.WriteCloser based on the configured compression type.
func (*Option) GetDecompressor ¶ added in v2.1.0
func (opt *Option) GetDecompressor(r io.ReadCloser, encoding string) (io.ReadCloser, error)
GetDecompressor returns an appropriate io.Reader for the given encoding.
func (*Option) GetFile ¶
GetFile returns the currently configured *os.File, if any. Returns nil if no file has been set. The returned file may be either opened or closed depending on the stage of request processing.
func (*Option) GetMaxRedirects ¶
func (*Option) GetProgressTracking ¶ added in v2.1.0
func (opt *Option) GetProgressTracking() ProgressTracking
GetProgressTracking returns the current progress tracking setting.
func (*Option) GetWriter ¶
func (opt *Option) GetWriter() io.WriteCloser
GetWriter returns the currently configured io.WriteCloser instance.
func (*Option) HasFileHandle ¶
HasFileHandle returns true if there is currently a file configured for use with this Option instance. This can be used to check if file operations should be performed during request processing.
func (*Option) InferContentType ¶
InferContentType determines the MIME type of a file based on its content and extension. If it is unable to determine a MIME type, it defaults to application/octet-stream.
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.
func (*Option) Log ¶
Log logs a message with the configured logger if verbose logging is enabled. The message will be logged at INFO level with any additional arguments provided.
func (*Option) Merge ¶
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) PrepareFile ¶
PrepareFile sets up a file for upload by opening it, checking its existence, setting metadata like size and content type, and configuring appropriate headers. It takes a filename string as input and returns an error if the file cannot be accessed, doesn't exist, or fails to open. The method also automatically sets Content-Disposition headers appropriate for file uploads.
func (*Option) Redirects ¶
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) ReopenFile ¶
ReopenFile attempts to reopen a previously closed file using the stored filename. This is particularly useful during redirect handling when a file needs to be re-read. Returns the reopened file and any error encountered. Logs the reopening attempt through the configured logger.
func (*Option) SetBufferOutput ¶
func (opt *Option) SetBufferOutput()
SetBufferOutput configures the response writer to write responses to an in-memory buffer.
func (*Option) SetClient ¶
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 ¶ added in v2.2.0
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 ¶
SetDownloadBufferSize configures the buffer size used when downloading files. The size must be positive; otherwise, the setting will be ignored.
func (*Option) SetFile ¶
SetFile configures an already-opened file for use with the client. It takes an *os.File pointer and sets internal metadata like filename and filesize. Unlike PrepareFile, this method assumes the file is already opened and valid.
func (*Option) SetFileOutput ¶
SetFileOutput configures the response writer to write responses to a file at the specified path.
func (*Option) SetLogger ¶
SetLogger configures a custom logger and enables verbose logging. The provided logger will replace any existing logger configuration.
func (*Option) SetMaxRedirects ¶
func (*Option) SetMaxResponseHeaderBytes ¶ added in v2.2.0
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. This setting is applied to the Transport.
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) SetProgressTracking ¶ added in v2.2.0
func (opt *Option) SetProgressTracking(pt ProgressTracking) *Option
SetProgressTracking sets the progress tracking mode.
func (*Option) SetProtocol ¶ added in v2.2.0
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 ¶
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) SetTransport ¶
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 ¶ added in v2.2.0
SetUploadBufferSize configures the buffer size used when uploading files. The size must be positive; otherwise, the setting will be ignored.
func (*Option) TrackAfterCompression ¶ added in v2.1.0
TrackAfterCompression sets progress tracking to occur after data compression. This tracks actual transfer size but not original data size.
func (*Option) TrackBeforeCompression ¶ added in v2.1.0
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()
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 ¶ added in v2.1.0
func (opt *Option) UsePerRequestClient()
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 ¶ added in v2.1.0
func (opt *Option) UseSharedClient()
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()
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.
type ProgressTracking ¶ added in v2.1.0
type ProgressTracking int
const ( TrackBeforeCompression ProgressTracking = iota TrackAfterCompression )
type Protocol ¶ added in v2.2.0
type Protocol int
Protocol defines which HTTP protocol versions to use for requests. This type leverages the 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 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 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 ¶
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
Determine if the bytes.Buffer is empty