Loading documentation...
Loading documentation...
Loading documentation...
Complete API documentation for the middleware package.
Import Path: github.com/kolosys/helix/middleware
Package middleware provides HTTP middleware for the Helix framework.
RequestIDHeader
RequestIDHeader is the default header name for the request ID.
const RequestIDHeader = "X-Request-ID"BasicAuthConfig configures the BasicAuth middleware.
// Create a new BasicAuthConfig
basicauthconfig := BasicAuthConfig{
Validator: /* value */,
Realm: "example",
SkipFunc: /* value */,
}type BasicAuthConfig struct {
Validator func(username, password string) bool
Realm string
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Validator | func(username, password string) bool | Validator is a function that validates the username and password. Return true if the credentials are valid. |
| Realm | string | Realm is the authentication realm displayed in the browser. Default: "Restricted" |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if authentication should be skipped. |
CORSConfig configures the CORS middleware.
// Create a new CORSConfig
corsconfig := CORSConfig{
AllowOrigins: [],
AllowOriginFunc: /* value */,
AllowMethods: [],
AllowHeaders: [],
ExposeHeaders: [],
AllowCredentials: true,
MaxAge: 42,
}type CORSConfig struct {
AllowOrigins []string
AllowOriginFunc func(origin string) bool
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge int
}| Field | Type | Description |
|---|---|---|
| AllowOrigins | []string | AllowOrigins is a list of origins that are allowed. Use "*" to allow all origins. Default: [] |
| AllowOriginFunc | func(origin string) bool | AllowOriginFunc is a custom function to validate the origin. If set, AllowOrigins is ignored. |
| AllowMethods | []string | AllowMethods is a list of methods that are allowed. Default: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS |
| AllowHeaders | []string | AllowHeaders is a list of headers that are allowed. Default: Origin, Content-Type, Accept, Authorization |
| ExposeHeaders | []string | ExposeHeaders is a list of headers that are exposed to the client. Default: [] |
| AllowCredentials | bool | AllowCredentials indicates whether credentials are allowed. Default: false |
| MaxAge | int | MaxAge is the maximum age (in seconds) of the preflight cache. Default: 0 (no caching) |
DefaultCORSConfig returns the default CORS configuration.
func DefaultCORSConfig() CORSConfigParameters: None
Returns:
CacheConfig configures the Cache middleware.
// Create a new CacheConfig
cacheconfig := CacheConfig{
MaxAge: 42,
SMaxAge: 42,
Public: true,
Private: true,
NoCache: true,
NoStore: true,
NoTransform: true,
MustRevalidate: true,
ProxyRevalidate: true,
Immutable: true,
StaleWhileRevalidate: 42,
StaleIfError: 42,
SkipFunc: /* value */,
VaryHeaders: [],
}type CacheConfig struct {
MaxAge int
SMaxAge int
Public bool
Private bool
NoCache bool
NoStore bool
NoTransform bool
MustRevalidate bool
ProxyRevalidate bool
Immutable bool
StaleWhileRevalidate int
StaleIfError int
SkipFunc func(r *http.Request) bool
VaryHeaders []string
}| Field | Type | Description |
|---|---|---|
| MaxAge | int | MaxAge sets the max-age directive in seconds. Default: 0 (not set) |
| SMaxAge | int | SMaxAge sets the s-maxage directive in seconds (for shared caches). Default: 0 (not set) |
| Public | bool | Public indicates the response can be cached by any cache. Default: false |
| Private | bool | Private indicates the response is for a single user. Default: false |
| NoCache | bool | NoCache indicates the response must be revalidated before use. Default: false |
| NoStore | bool | NoStore indicates the response must not be stored. Default: false |
| NoTransform | bool | NoTransform indicates the response must not be transformed. Default: false |
| MustRevalidate | bool | MustRevalidate indicates stale responses must be revalidated. Default: false |
| ProxyRevalidate | bool | ProxyRevalidate is like MustRevalidate but for shared caches. Default: false |
| Immutable | bool | Immutable indicates the response body will not change. Default: false |
| StaleWhileRevalidate | int | StaleWhileRevalidate allows serving stale content while revalidating. Value is in seconds. Default: 0 (not set) |
| StaleIfError | int | StaleIfError allows serving stale content if there's an error. Value is in seconds. Default: 0 (not set) |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if cache headers should be skipped. |
| VaryHeaders | []string | VaryHeaders is a list of headers to include in the Vary header. |
DefaultCacheConfig returns the default Cache configuration.
func DefaultCacheConfig() CacheConfigParameters: None
Returns:
CompressConfig configures the Compress middleware.
// Create a new CompressConfig
compressconfig := CompressConfig{
Level: 42,
MinSize: 42,
Types: [],
SkipFunc: /* value */,
}type CompressConfig struct {
Level int
MinSize int
Types []string
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Level | int | Level is the compression level. Valid levels: -1 (default), 0 (no compression), 1 (best speed) to 9 (best compression) Default: -1 (gzip.DefaultCompression) |
| MinSize | int | MinSize is the minimum size in bytes to trigger compression. Default: 1024 (1KB) |
| Types | []string | Types is a list of content types to compress. Default: text/*, application/json, application/javascript, application/xml |
| SkipFunc | func(r *http.Request) bool | SkipFunc is a function that determines if compression should be skipped. |
DefaultCompressConfig returns the default Compress configuration.
func DefaultCompressConfig() CompressConfigParameters: None
Returns:
ETagConfig configures the ETag middleware.
// Create a new ETagConfig
etagconfig := ETagConfig{
Weak: true,
SkipFunc: /* value */,
}type ETagConfig struct {
Weak bool
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Weak | bool | Weak indicates whether to generate weak ETags. Weak ETags are prefixed with W/ and indicate semantic equivalence. Default: false (strong ETags) |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if ETag generation should be skipped. |
DefaultETagConfig returns the default ETag configuration.
func DefaultETagConfig() ETagConfigParameters: None
Returns:
LogFormat represents a predefined log format.
// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat stringLogOutputFunc is a callback that receives log values and outputs them. This is the single output mechanism - use helpers for common formats.
// Example usage of LogOutputFunc
var value LogOutputFunc
// Initialize with appropriate valuetype LogOutputFunc func(v LogValues)TextOutput returns a LogOutputFunc that writes Morgan.js-style formatted logs.
func TextOutput(w io.Writer, format LogFormat) LogOutputFuncParameters:
w (io.Writer)format (LogFormat)Returns:
TextOutputCustom returns a LogOutputFunc with a custom format string.
func TextOutputCustom(w io.Writer, format string, opts ...TextOutputOptions) LogOutputFuncParameters:
w (io.Writer)format (string)opts (...TextOutputOptions)Returns:
TextOutputWithOptions returns a LogOutputFunc with custom options.
func TextOutputWithOptions(w io.Writer, format LogFormat, opts TextOutputOptions) LogOutputFuncParameters:
w (io.Writer)format (LogFormat)opts (TextOutputOptions)Returns:
LogValues contains all extracted request/response data for logging.
// Create a new LogValues
logvalues := LogValues{
Method: "example",
Path: "example",
URI: "example",
Host: "example",
Protocol: "example",
RemoteIP: "example",
UserAgent: "example",
Referer: "example",
ContentLength: 42,
ContentType: "example",
Status: 42,
ResponseSize: 42,
Latency: /* value */,
Error: error{},
RequestID: "example",
StartTime: /* value */,
Headers: map[],
QueryParams: map[],
FormValues: map[],
CustomFields: map[],
}type LogValues struct {
Method string
Path string
URI string
Host string
Protocol string
RemoteIP string
UserAgent string
Referer string
ContentLength int64
ContentType string
Status int
ResponseSize int
Latency time.Duration
Error error
RequestID string
StartTime time.Time
Headers map[string]string
QueryParams map[string]string
FormValues map[string]string
CustomFields map[string]string
}| Field | Type | Description |
|---|---|---|
| Method | string | |
| Path | string | |
| URI | string | |
| Host | string | |
| Protocol | string | |
| RemoteIP | string | |
| UserAgent | string | |
| Referer | string | |
| ContentLength | int64 | |
| ContentType | string | |
| Status | int | |
| ResponseSize | int | |
| Latency | time.Duration | |
| Error | error | |
| RequestID | string | |
| StartTime | time.Time | |
| Headers | map[string]string | |
| QueryParams | map[string]string | |
| FormValues | map[string]string | |
| CustomFields | map[string]string |
LoggerConfig configures the Logger middleware.
// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Output: LogOutputFunc{},
Skip: /* value */,
Fields: map[],
CustomTokens: map[],
LogHeaders: [],
LogQueryParams: [],
LogFormValues: [],
CaptureBody: true,
MaxBodySize: 42,
}type LoggerConfig struct {
Output LogOutputFunc
Skip func(r *http.Request) bool
Fields map[string]string
CustomTokens map[string]TokenExtractor
LogHeaders []string
LogQueryParams []string
LogFormValues []string
CaptureBody bool
MaxBodySize int64
}| Field | Type | Description |
|---|---|---|
| Output | LogOutputFunc | Output is the callback that receives log values. Required. Use TextOutput() for Morgan.js-style formatting. Use helix.StructuredOutput() for logs package integration. Or provide your own function for custom logging. |
| Skip | func(r *http.Request) bool | Skip determines if logging should be skipped for a request. |
| Fields | map[string]string | Fields maps custom field names to their sources. Sources: "header:Name", "query:param", "cookie:name" |
| CustomTokens | map[string]TokenExtractor | CustomTokens maps names to extractor functions for body/context data. |
| LogHeaders | []string | LogHeaders specifies request headers to extract into Headers map. |
| LogQueryParams | []string | LogQueryParams specifies query parameters to extract. |
| LogFormValues | []string | LogFormValues specifies form values to extract. |
| CaptureBody | bool | CaptureBody enables request body capture for CustomTokens. |
| MaxBodySize | int64 | MaxBodySize limits captured body size. Default: 64KB. |
Middleware is a function that wraps an http.Handler to provide additional functionality.
// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware func(next http.Handler) http.HandlerAPI returns a middleware bundle suitable for JSON API servers. Includes: RequestID, Recover, and CORS. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func API() []MiddlewareParameters: None
Returns:
APIWithCORS returns a middleware bundle suitable for JSON API servers with a custom CORS configuration. Includes: RequestID, Recover, and CORS with config. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func APIWithCORS(cors CORSConfig) []MiddlewareParameters:
cors (CORSConfig)Returns:
BasicAuth returns a BasicAuth middleware with the given username and password. Uses constant-time comparison to prevent timing attacks.
func BasicAuth(username, password string) MiddlewareParameters:
username (string)password (string)Returns:
BasicAuthUsers returns a BasicAuth middleware that validates against a map of users. The map key is the username and the value is the password.
func BasicAuthUsers(users map[string]string) MiddlewareParameters:
users (map[string]string)Returns:
BasicAuthWithConfig returns a BasicAuth middleware with the given configuration.
func BasicAuthWithConfig(config BasicAuthConfig) MiddlewareParameters:
config (BasicAuthConfig)Returns:
BasicAuthWithValidator returns a BasicAuth middleware with a custom validator.
func BasicAuthWithValidator(validator func(username, password string) bool) MiddlewareParameters:
validator (func(username, password string) bool)Returns:
CORS returns a CORS middleware with default configuration.
func CORS() MiddlewareParameters: None
Returns:
CORSAllowAll returns a CORS middleware that allows all origins, methods, and headers.
func CORSAllowAll() MiddlewareParameters: None
Returns:
CORSWithConfig returns a CORS middleware with the given configuration.
func CORSWithConfig(config CORSConfig) MiddlewareParameters:
config (CORSConfig)Returns:
Cache returns a Cache middleware with the given max-age in seconds.
func Cache(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CacheImmutable returns a Cache middleware for immutable content.
func CacheImmutable(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CachePrivate returns a Cache middleware with private caching.
func CachePrivate(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CachePublic returns a Cache middleware with public caching.
func CachePublic(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CacheWithConfig returns a Cache middleware with the given configuration.
func CacheWithConfig(config CacheConfig) MiddlewareParameters:
config (CacheConfig)Returns:
Chain creates a new middleware chain from the given middlewares. The first middleware in the chain is the outermost (executed first on request, last on response).
func Chain(middlewares ...Middleware) MiddlewareParameters:
middlewares (...Middleware)Returns:
Compress returns a middleware that compresses responses using gzip or deflate.
func Compress() MiddlewareParameters: None
Returns:
CompressWithConfig returns a Compress middleware with the given configuration.
func CompressWithConfig(config CompressConfig) MiddlewareParameters:
config (CompressConfig)Returns:
CompressWithLevel returns a Compress middleware with the given compression level.
func CompressWithLevel(level int) MiddlewareParameters:
level (int)Returns:
Development returns a middleware bundle suitable for development. Includes: RequestID, Recover. Add logging via helix.LoggerMiddleware with your preferred RequestLogger. This is the same as what helix.Default() uses (plus logging).
func Development() []MiddlewareParameters: None
Returns:
ETag returns an ETag middleware with default configuration.
func ETag() MiddlewareParameters: None
Returns:
ETagWeak returns an ETag middleware that generates weak ETags.
func ETagWeak() MiddlewareParameters: None
Returns:
ETagWithConfig returns an ETag middleware with the given configuration.
func ETagWithConfig(config ETagConfig) MiddlewareParameters:
config (ETagConfig)Returns:
Logger returns a middleware with dev format text output.
func Logger() MiddlewareParameters: None
Returns:
LoggerWithConfig returns a Logger middleware with the given configuration.
func LoggerWithConfig(config LoggerConfig) MiddlewareParameters:
config (LoggerConfig)Returns:
Minimal returns a minimal middleware bundle with only essential middleware. Includes: Recover.
func Minimal() []MiddlewareParameters: None
Returns:
NoCache returns a middleware that disables caching.
func NoCache() MiddlewareParameters: None
Returns:
Production returns a middleware bundle suitable for production environments. Includes: RequestID, Recover. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func Production() []MiddlewareParameters: None
Returns:
ProfileMiddleware wraps a middleware with profiling instrumentation.
func ProfileMiddleware(name string, mw Middleware) MiddlewareParameters:
name (string)mw (Middleware)Returns:
RateLimit returns a rate limiting middleware with the given rate and burst.
func RateLimit(rate float64, burst int) MiddlewareParameters:
rate (float64)burst (int)Returns:
RateLimitWithConfig returns a RateLimit middleware with the given configuration.
func RateLimitWithConfig(config RateLimitConfig) MiddlewareParameters:
config (RateLimitConfig)Returns:
Recover returns a middleware that recovers from panics. It logs the panic and stack trace, then returns a 500 Internal Server Error.
func Recover() MiddlewareParameters: None
Returns:
RecoverWithConfig returns a Recover middleware with the given configuration.
func RecoverWithConfig(config RecoverConfig) MiddlewareParameters:
config (RecoverConfig)Returns:
RequestID returns a middleware that generates or propagates a request ID. The request ID is stored in the request context and the response header.
func RequestID() MiddlewareParameters: None
Returns:
RequestIDWithConfig returns a RequestID middleware with the given configuration.
func RequestIDWithConfig(config RequestIDConfig) MiddlewareParameters:
config (RequestIDConfig)Returns:
Secure returns a middleware bundle with security-focused middleware. Includes: RequestID, Recover, RateLimit. Add logging via helix.LoggerMiddleware with your preferred RequestLogger. Note: You should also add CORS and authentication middleware as needed.
func Secure(rate float64, burst int) []MiddlewareParameters:
rate (float64) - requests per second allowed
burst (int) - maximum burst size
Returns:
Timeout returns a middleware that adds a timeout to requests.
func Timeout(timeout time.Duration) MiddlewareParameters:
timeout (time.Duration)Returns:
TimeoutWithConfig returns a Timeout middleware with the given configuration.
func TimeoutWithConfig(config TimeoutConfig) MiddlewareParameters:
config (TimeoutConfig)Returns:
Web returns a middleware bundle suitable for web applications. Includes: RequestID, Recover, and Compress. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func Web() []MiddlewareParameters: None
Returns:
MiddlewareProfile contains profiling information for a middleware.
// Create a new MiddlewareProfile
middlewareprofile := MiddlewareProfile{
Name: "example",
Duration: /* value */,
Allocs: 42,
Bytes: 42,
}type MiddlewareProfile struct {
Name string
Duration time.Duration
Allocs uint64
Bytes uint64
}| Field | Type | Description |
|---|---|---|
| Name | string | |
| Duration | time.Duration | |
| Allocs | uint64 | |
| Bytes | uint64 |
RateLimitConfig configures the RateLimit middleware.
// Create a new RateLimitConfig
ratelimitconfig := RateLimitConfig{
Rate: 3.14,
Burst: 42,
KeyFunc: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
CleanupInterval: /* value */,
ExpirationTime: /* value */,
}type RateLimitConfig struct {
Rate float64
Burst int
KeyFunc func(r *http.Request) string
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
CleanupInterval time.Duration
ExpirationTime time.Duration
}| Field | Type | Description |
|---|---|---|
| Rate | float64 | Rate is the number of requests allowed per second. Default: 100 |
| Burst | int | Burst is the maximum number of requests allowed in a burst. Default: 10 |
| KeyFunc | func(r *http.Request) string | KeyFunc extracts the rate limit key from the request. Default: uses client IP address |
| Handler | http.HandlerFunc | Handler is called when the rate limit is exceeded. If nil, a default 429 Too Many Requests response is sent. |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if rate limiting should be skipped. |
| CleanupInterval | time.Duration | CleanupInterval is the interval for cleaning up expired entries. Default: 1 minute |
| ExpirationTime | time.Duration | ExpirationTime is how long to keep entries after last access. Default: 5 minutes |
DefaultRateLimitConfig returns the default RateLimit configuration.
func DefaultRateLimitConfig() RateLimitConfigParameters: None
Returns:
RecoverConfig configures the Recover middleware.
// Create a new RecoverConfig
recoverconfig := RecoverConfig{
PrintStack: true,
StackSize: 42,
Output: /* value */,
Handler: /* value */,
}type RecoverConfig struct {
PrintStack bool
StackSize int
Output io.Writer
Handler func(w http.ResponseWriter, r *http.Request, err any)
}| Field | Type | Description |
|---|---|---|
| PrintStack | bool | PrintStack enables printing the stack trace when a panic occurs. Default: true |
| StackSize | int | StackSize is the maximum size of the stack trace buffer. Default: 4KB |
| Output | io.Writer | Output is the writer to output the panic message to. Default: os.Stderr |
| Handler | func(w http.ResponseWriter, r *http.Request, err any) | Handler is a custom function to handle panics. If set, it will be called instead of the default behavior. The handler should write the response and return. |
DefaultRecoverConfig returns the default configuration for Recover.
func DefaultRecoverConfig() RecoverConfigParameters: None
Returns:
RequestIDConfig configures the RequestID middleware.
// Create a new RequestIDConfig
requestidconfig := RequestIDConfig{
Header: "example",
Generator: /* value */,
TargetHeader: "example",
}type RequestIDConfig struct {
Header string
Generator func() string
TargetHeader string
}| Field | Type | Description |
|---|---|---|
| Header | string | Header is the name of the header to read/write the request ID. Default: "X-Request-ID" |
| Generator | func() string | Generator is a function that generates a new request ID. Default: generates a random 16-byte hex string |
| TargetHeader | string | TargetHeader is the header name to set on the response. Default: same as Header |
DefaultRequestIDConfig returns the default configuration for RequestID.
func DefaultRequestIDConfig() RequestIDConfigParameters: None
Returns:
--- Text Output Helpers (Morgan.js style) --- TextOutputOptions configures text output formatting.
// Create a new TextOutputOptions
textoutputoptions := TextOutputOptions{
TimeFormat: "example",
DisableColors: true,
JSONPretty: true,
}type TextOutputOptions struct {
TimeFormat string
DisableColors bool
JSONPretty bool
}| Field | Type | Description |
|---|---|---|
| TimeFormat | string | |
| DisableColors | bool | |
| JSONPretty | bool | for LogFormatJSON |
TimeoutConfig configures the Timeout middleware.
// Create a new TimeoutConfig
timeoutconfig := TimeoutConfig{
Timeout: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
}type TimeoutConfig struct {
Timeout time.Duration
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Timeout | time.Duration | Timeout is the maximum duration for the request. Default: 30 seconds |
| Handler | http.HandlerFunc | Handler is called when the request times out. If nil, a default 503 Service Unavailable response is sent. |
| SkipFunc | func(r *http.Request) bool | SkipFunc is a function that determines if timeout should be skipped. If it returns true, no timeout is applied. |
DefaultTimeoutConfig returns the default Timeout configuration.
func DefaultTimeoutConfig() TimeoutConfigParameters: None
Returns:
TokenExtractor extracts a custom value from the request.
// Example usage of TokenExtractor
var value TokenExtractor
// Initialize with appropriate valuetype TokenExtractor func(r *http.Request, body []byte) stringContextValueExtractor creates a TokenExtractor for context values.
func ContextValueExtractor(key any) TokenExtractorParameters:
key (any)Returns:
FormValueExtractor creates a TokenExtractor for form fields.
func FormValueExtractor(field string) TokenExtractorParameters:
field (string)Returns:
JSONBodyExtractor creates a TokenExtractor for JSON body fields.
func JSONBodyExtractor(path string) TokenExtractorParameters:
path (string)Returns:
ETagFromContent generates an ETag from content.
func ETagFromContent(content []byte, weak bool) stringParameters:
| Parameter | Type | Description |
|---|---|---|
content | []byte | |
weak | bool |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of ETagFromContent
result := ETagFromContent(/* parameters */)ETagFromString generates an ETag from a string.
func ETagFromString(s string, weak bool) stringParameters:
| Parameter | Type | Description |
|---|---|---|
s | string | |
weak | bool |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of ETagFromString
result := ETagFromString(/* parameters */)ETagFromVersion generates an ETag from a version number.
func ETagFromVersion(version int64, weak bool) stringParameters:
| Parameter | Type | Description |
|---|---|---|
version | int64 | |
weak | bool |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of ETagFromVersion
result := ETagFromVersion(/* parameters */)GetProfiles returns all middleware profiles.
func GetProfiles() map[string]*MiddlewareProfileParameters: None
Returns:
| Type | Description |
|---|---|
map[string]*MiddlewareProfile |
Example:
// Example usage of GetProfiles
result := GetProfiles(/* parameters */)GetRequestID retrieves the request ID from the context. Returns an empty string if no request ID is set.
func GetRequestID(ctx context.Context) stringParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of GetRequestID
result := GetRequestID(/* parameters */)GetRequestIDFromRequest retrieves the request ID from the request context.
func GetRequestIDFromRequest(r *http.Request) stringParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of GetRequestIDFromRequest
result := GetRequestIDFromRequest(/* parameters */)ResetProfiles clears all profiling data.
func ResetProfiles()Parameters: None
Returns: None
Example:
// Example usage of ResetProfiles
result := ResetProfiles(/* parameters */)SetCacheControl sets the Cache-Control header on the response.
func SetCacheControl(w http.ResponseWriter, value string)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
value | string |
Returns: None
Example:
// Example usage of SetCacheControl
result := SetCacheControl(/* parameters */)SetExpires sets the Expires header on the response.
func SetExpires(w http.ResponseWriter, t time.Time)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
t | time.Time |
Returns: None
Example:
// Example usage of SetExpires
result := SetExpires(/* parameters */)SetLastModified sets the Last-Modified header on the response.
func SetLastModified(w http.ResponseWriter, t time.Time)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
t | time.Time |
Returns: None
Example:
// Example usage of SetLastModified
result := SetLastModified(/* parameters */)Complete API documentation for the middleware package.
Import Path: github.com/kolosys/helix/middleware
Package middleware provides HTTP middleware for the Helix framework.
RequestIDHeader
RequestIDHeader is the default header name for the request ID.
const RequestIDHeader = "X-Request-ID"BasicAuthConfig configures the BasicAuth middleware.
// Create a new BasicAuthConfig
basicauthconfig := BasicAuthConfig{
Validator: /* value */,
Realm: "example",
SkipFunc: /* value */,
}type BasicAuthConfig struct {
Validator func(username, password string) bool
Realm string
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Validator | func(username, password string) bool | Validator is a function that validates the username and password. Return true if the credentials are valid. |
| Realm | string | Realm is the authentication realm displayed in the browser. Default: "Restricted" |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if authentication should be skipped. |
CORSConfig configures the CORS middleware.
// Create a new CORSConfig
corsconfig := CORSConfig{
AllowOrigins: [],
AllowOriginFunc: /* value */,
AllowMethods: [],
AllowHeaders: [],
ExposeHeaders: [],
AllowCredentials: true,
MaxAge: 42,
}type CORSConfig struct {
AllowOrigins []string
AllowOriginFunc func(origin string) bool
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge int
}| Field | Type | Description |
|---|---|---|
| AllowOrigins | []string | AllowOrigins is a list of origins that are allowed. Use "*" to allow all origins. Default: [] |
| AllowOriginFunc | func(origin string) bool | AllowOriginFunc is a custom function to validate the origin. If set, AllowOrigins is ignored. |
| AllowMethods | []string | AllowMethods is a list of methods that are allowed. Default: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS |
| AllowHeaders | []string | AllowHeaders is a list of headers that are allowed. Default: Origin, Content-Type, Accept, Authorization |
| ExposeHeaders | []string | ExposeHeaders is a list of headers that are exposed to the client. Default: [] |
| AllowCredentials | bool | AllowCredentials indicates whether credentials are allowed. Default: false |
| MaxAge | int | MaxAge is the maximum age (in seconds) of the preflight cache. Default: 0 (no caching) |
DefaultCORSConfig returns the default CORS configuration.
func DefaultCORSConfig() CORSConfigParameters: None
Returns:
CacheConfig configures the Cache middleware.
// Create a new CacheConfig
cacheconfig := CacheConfig{
MaxAge: 42,
SMaxAge: 42,
Public: true,
Private: true,
NoCache: true,
NoStore: true,
NoTransform: true,
MustRevalidate: true,
ProxyRevalidate: true,
Immutable: true,
StaleWhileRevalidate: 42,
StaleIfError: 42,
SkipFunc: /* value */,
VaryHeaders: [],
}type CacheConfig struct {
MaxAge int
SMaxAge int
Public bool
Private bool
NoCache bool
NoStore bool
NoTransform bool
MustRevalidate bool
ProxyRevalidate bool
Immutable bool
StaleWhileRevalidate int
StaleIfError int
SkipFunc func(r *http.Request) bool
VaryHeaders []string
}| Field | Type | Description |
|---|---|---|
| MaxAge | int | MaxAge sets the max-age directive in seconds. Default: 0 (not set) |
| SMaxAge | int | SMaxAge sets the s-maxage directive in seconds (for shared caches). Default: 0 (not set) |
| Public | bool | Public indicates the response can be cached by any cache. Default: false |
| Private | bool | Private indicates the response is for a single user. Default: false |
| NoCache | bool | NoCache indicates the response must be revalidated before use. Default: false |
| NoStore | bool | NoStore indicates the response must not be stored. Default: false |
| NoTransform | bool | NoTransform indicates the response must not be transformed. Default: false |
| MustRevalidate | bool | MustRevalidate indicates stale responses must be revalidated. Default: false |
| ProxyRevalidate | bool | ProxyRevalidate is like MustRevalidate but for shared caches. Default: false |
| Immutable | bool | Immutable indicates the response body will not change. Default: false |
| StaleWhileRevalidate | int | StaleWhileRevalidate allows serving stale content while revalidating. Value is in seconds. Default: 0 (not set) |
| StaleIfError | int | StaleIfError allows serving stale content if there's an error. Value is in seconds. Default: 0 (not set) |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if cache headers should be skipped. |
| VaryHeaders | []string | VaryHeaders is a list of headers to include in the Vary header. |
DefaultCacheConfig returns the default Cache configuration.
func DefaultCacheConfig() CacheConfigParameters: None
Returns:
CompressConfig configures the Compress middleware.
// Create a new CompressConfig
compressconfig := CompressConfig{
Level: 42,
MinSize: 42,
Types: [],
SkipFunc: /* value */,
}type CompressConfig struct {
Level int
MinSize int
Types []string
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Level | int | Level is the compression level. Valid levels: -1 (default), 0 (no compression), 1 (best speed) to 9 (best compression) Default: -1 (gzip.DefaultCompression) |
| MinSize | int | MinSize is the minimum size in bytes to trigger compression. Default: 1024 (1KB) |
| Types | []string | Types is a list of content types to compress. Default: text/*, application/json, application/javascript, application/xml |
| SkipFunc | func(r *http.Request) bool | SkipFunc is a function that determines if compression should be skipped. |
DefaultCompressConfig returns the default Compress configuration.
func DefaultCompressConfig() CompressConfigParameters: None
Returns:
ETagConfig configures the ETag middleware.
// Create a new ETagConfig
etagconfig := ETagConfig{
Weak: true,
SkipFunc: /* value */,
}type ETagConfig struct {
Weak bool
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Weak | bool | Weak indicates whether to generate weak ETags. Weak ETags are prefixed with W/ and indicate semantic equivalence. Default: false (strong ETags) |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if ETag generation should be skipped. |
DefaultETagConfig returns the default ETag configuration.
func DefaultETagConfig() ETagConfigParameters: None
Returns:
LogFormat represents a predefined log format.
// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat stringLogOutputFunc is a callback that receives log values and outputs them. This is the single output mechanism - use helpers for common formats.
// Example usage of LogOutputFunc
var value LogOutputFunc
// Initialize with appropriate valuetype LogOutputFunc func(v LogValues)TextOutput returns a LogOutputFunc that writes Morgan.js-style formatted logs.
func TextOutput(w io.Writer, format LogFormat) LogOutputFuncParameters:
w (io.Writer)format (LogFormat)Returns:
TextOutputCustom returns a LogOutputFunc with a custom format string.
func TextOutputCustom(w io.Writer, format string, opts ...TextOutputOptions) LogOutputFuncParameters:
w (io.Writer)format (string)opts (...TextOutputOptions)Returns:
TextOutputWithOptions returns a LogOutputFunc with custom options.
func TextOutputWithOptions(w io.Writer, format LogFormat, opts TextOutputOptions) LogOutputFuncParameters:
w (io.Writer)format (LogFormat)opts (TextOutputOptions)Returns:
LogValues contains all extracted request/response data for logging.
// Create a new LogValues
logvalues := LogValues{
Method: "example",
Path: "example",
URI: "example",
Host: "example",
Protocol: "example",
RemoteIP: "example",
UserAgent: "example",
Referer: "example",
ContentLength: 42,
ContentType: "example",
Status: 42,
ResponseSize: 42,
Latency: /* value */,
Error: error{},
RequestID: "example",
StartTime: /* value */,
Headers: map[],
QueryParams: map[],
FormValues: map[],
CustomFields: map[],
}type LogValues struct {
Method string
Path string
URI string
Host string
Protocol string
RemoteIP string
UserAgent string
Referer string
ContentLength int64
ContentType string
Status int
ResponseSize int
Latency time.Duration
Error error
RequestID string
StartTime time.Time
Headers map[string]string
QueryParams map[string]string
FormValues map[string]string
CustomFields map[string]string
}| Field | Type | Description |
|---|---|---|
| Method | string | |
| Path | string | |
| URI | string | |
| Host | string | |
| Protocol | string | |
| RemoteIP | string | |
| UserAgent | string | |
| Referer | string | |
| ContentLength | int64 | |
| ContentType | string | |
| Status | int | |
| ResponseSize | int | |
| Latency | time.Duration | |
| Error | error | |
| RequestID | string | |
| StartTime | time.Time | |
| Headers | map[string]string | |
| QueryParams | map[string]string | |
| FormValues | map[string]string | |
| CustomFields | map[string]string |
LoggerConfig configures the Logger middleware.
// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Output: LogOutputFunc{},
Skip: /* value */,
Fields: map[],
CustomTokens: map[],
LogHeaders: [],
LogQueryParams: [],
LogFormValues: [],
CaptureBody: true,
MaxBodySize: 42,
}type LoggerConfig struct {
Output LogOutputFunc
Skip func(r *http.Request) bool
Fields map[string]string
CustomTokens map[string]TokenExtractor
LogHeaders []string
LogQueryParams []string
LogFormValues []string
CaptureBody bool
MaxBodySize int64
}| Field | Type | Description |
|---|---|---|
| Output | LogOutputFunc | Output is the callback that receives log values. Required. Use TextOutput() for Morgan.js-style formatting. Use helix.StructuredOutput() for logs package integration. Or provide your own function for custom logging. |
| Skip | func(r *http.Request) bool | Skip determines if logging should be skipped for a request. |
| Fields | map[string]string | Fields maps custom field names to their sources. Sources: "header:Name", "query:param", "cookie:name" |
| CustomTokens | map[string]TokenExtractor | CustomTokens maps names to extractor functions for body/context data. |
| LogHeaders | []string | LogHeaders specifies request headers to extract into Headers map. |
| LogQueryParams | []string | LogQueryParams specifies query parameters to extract. |
| LogFormValues | []string | LogFormValues specifies form values to extract. |
| CaptureBody | bool | CaptureBody enables request body capture for CustomTokens. |
| MaxBodySize | int64 | MaxBodySize limits captured body size. Default: 64KB. |
Middleware is a function that wraps an http.Handler to provide additional functionality.
// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware func(next http.Handler) http.HandlerAPI returns a middleware bundle suitable for JSON API servers. Includes: RequestID, Recover, and CORS. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func API() []MiddlewareParameters: None
Returns:
APIWithCORS returns a middleware bundle suitable for JSON API servers with a custom CORS configuration. Includes: RequestID, Recover, and CORS with config. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func APIWithCORS(cors CORSConfig) []MiddlewareParameters:
cors (CORSConfig)Returns:
BasicAuth returns a BasicAuth middleware with the given username and password. Uses constant-time comparison to prevent timing attacks.
func BasicAuth(username, password string) MiddlewareParameters:
username (string)password (string)Returns:
BasicAuthUsers returns a BasicAuth middleware that validates against a map of users. The map key is the username and the value is the password.
func BasicAuthUsers(users map[string]string) MiddlewareParameters:
users (map[string]string)Returns:
BasicAuthWithConfig returns a BasicAuth middleware with the given configuration.
func BasicAuthWithConfig(config BasicAuthConfig) MiddlewareParameters:
config (BasicAuthConfig)Returns:
BasicAuthWithValidator returns a BasicAuth middleware with a custom validator.
func BasicAuthWithValidator(validator func(username, password string) bool) MiddlewareParameters:
validator (func(username, password string) bool)Returns:
CORS returns a CORS middleware with default configuration.
func CORS() MiddlewareParameters: None
Returns:
CORSAllowAll returns a CORS middleware that allows all origins, methods, and headers.
func CORSAllowAll() MiddlewareParameters: None
Returns:
CORSWithConfig returns a CORS middleware with the given configuration.
func CORSWithConfig(config CORSConfig) MiddlewareParameters:
config (CORSConfig)Returns:
Cache returns a Cache middleware with the given max-age in seconds.
func Cache(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CacheImmutable returns a Cache middleware for immutable content.
func CacheImmutable(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CachePrivate returns a Cache middleware with private caching.
func CachePrivate(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CachePublic returns a Cache middleware with public caching.
func CachePublic(maxAge int) MiddlewareParameters:
maxAge (int)Returns:
CacheWithConfig returns a Cache middleware with the given configuration.
func CacheWithConfig(config CacheConfig) MiddlewareParameters:
config (CacheConfig)Returns:
Chain creates a new middleware chain from the given middlewares. The first middleware in the chain is the outermost (executed first on request, last on response).
func Chain(middlewares ...Middleware) MiddlewareParameters:
middlewares (...Middleware)Returns:
Compress returns a middleware that compresses responses using gzip or deflate.
func Compress() MiddlewareParameters: None
Returns:
CompressWithConfig returns a Compress middleware with the given configuration.
func CompressWithConfig(config CompressConfig) MiddlewareParameters:
config (CompressConfig)Returns:
CompressWithLevel returns a Compress middleware with the given compression level.
func CompressWithLevel(level int) MiddlewareParameters:
level (int)Returns:
Development returns a middleware bundle suitable for development. Includes: RequestID, Recover. Add logging via helix.LoggerMiddleware with your preferred RequestLogger. This is the same as what helix.Default() uses (plus logging).
func Development() []MiddlewareParameters: None
Returns:
ETag returns an ETag middleware with default configuration.
func ETag() MiddlewareParameters: None
Returns:
ETagWeak returns an ETag middleware that generates weak ETags.
func ETagWeak() MiddlewareParameters: None
Returns:
ETagWithConfig returns an ETag middleware with the given configuration.
func ETagWithConfig(config ETagConfig) MiddlewareParameters:
config (ETagConfig)Returns:
Logger returns a middleware with dev format text output.
func Logger() MiddlewareParameters: None
Returns:
LoggerWithConfig returns a Logger middleware with the given configuration.
func LoggerWithConfig(config LoggerConfig) MiddlewareParameters:
config (LoggerConfig)Returns:
Minimal returns a minimal middleware bundle with only essential middleware. Includes: Recover.
func Minimal() []MiddlewareParameters: None
Returns:
NoCache returns a middleware that disables caching.
func NoCache() MiddlewareParameters: None
Returns:
Production returns a middleware bundle suitable for production environments. Includes: RequestID, Recover. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func Production() []MiddlewareParameters: None
Returns:
ProfileMiddleware wraps a middleware with profiling instrumentation.
func ProfileMiddleware(name string, mw Middleware) MiddlewareParameters:
name (string)mw (Middleware)Returns:
RateLimit returns a rate limiting middleware with the given rate and burst.
func RateLimit(rate float64, burst int) MiddlewareParameters:
rate (float64)burst (int)Returns:
RateLimitWithConfig returns a RateLimit middleware with the given configuration.
func RateLimitWithConfig(config RateLimitConfig) MiddlewareParameters:
config (RateLimitConfig)Returns:
Recover returns a middleware that recovers from panics. It logs the panic and stack trace, then returns a 500 Internal Server Error.
func Recover() MiddlewareParameters: None
Returns:
RecoverWithConfig returns a Recover middleware with the given configuration.
func RecoverWithConfig(config RecoverConfig) MiddlewareParameters:
config (RecoverConfig)Returns:
RequestID returns a middleware that generates or propagates a request ID. The request ID is stored in the request context and the response header.
func RequestID() MiddlewareParameters: None
Returns:
RequestIDWithConfig returns a RequestID middleware with the given configuration.
func RequestIDWithConfig(config RequestIDConfig) MiddlewareParameters:
config (RequestIDConfig)Returns:
Secure returns a middleware bundle with security-focused middleware. Includes: RequestID, Recover, RateLimit. Add logging via helix.LoggerMiddleware with your preferred RequestLogger. Note: You should also add CORS and authentication middleware as needed.
func Secure(rate float64, burst int) []MiddlewareParameters:
rate (float64) - requests per second allowed
burst (int) - maximum burst size
Returns:
Timeout returns a middleware that adds a timeout to requests.
func Timeout(timeout time.Duration) MiddlewareParameters:
timeout (time.Duration)Returns:
TimeoutWithConfig returns a Timeout middleware with the given configuration.
func TimeoutWithConfig(config TimeoutConfig) MiddlewareParameters:
config (TimeoutConfig)Returns:
Web returns a middleware bundle suitable for web applications. Includes: RequestID, Recover, and Compress. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.
func Web() []MiddlewareParameters: None
Returns:
MiddlewareProfile contains profiling information for a middleware.
// Create a new MiddlewareProfile
middlewareprofile := MiddlewareProfile{
Name: "example",
Duration: /* value */,
Allocs: 42,
Bytes: 42,
}type MiddlewareProfile struct {
Name string
Duration time.Duration
Allocs uint64
Bytes uint64
}| Field | Type | Description |
|---|---|---|
| Name | string | |
| Duration | time.Duration | |
| Allocs | uint64 | |
| Bytes | uint64 |
RateLimitConfig configures the RateLimit middleware.
// Create a new RateLimitConfig
ratelimitconfig := RateLimitConfig{
Rate: 3.14,
Burst: 42,
KeyFunc: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
CleanupInterval: /* value */,
ExpirationTime: /* value */,
}type RateLimitConfig struct {
Rate float64
Burst int
KeyFunc func(r *http.Request) string
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
CleanupInterval time.Duration
ExpirationTime time.Duration
}| Field | Type | Description |
|---|---|---|
| Rate | float64 | Rate is the number of requests allowed per second. Default: 100 |
| Burst | int | Burst is the maximum number of requests allowed in a burst. Default: 10 |
| KeyFunc | func(r *http.Request) string | KeyFunc extracts the rate limit key from the request. Default: uses client IP address |
| Handler | http.HandlerFunc | Handler is called when the rate limit is exceeded. If nil, a default 429 Too Many Requests response is sent. |
| SkipFunc | func(r *http.Request) bool | SkipFunc determines if rate limiting should be skipped. |
| CleanupInterval | time.Duration | CleanupInterval is the interval for cleaning up expired entries. Default: 1 minute |
| ExpirationTime | time.Duration | ExpirationTime is how long to keep entries after last access. Default: 5 minutes |
DefaultRateLimitConfig returns the default RateLimit configuration.
func DefaultRateLimitConfig() RateLimitConfigParameters: None
Returns:
RecoverConfig configures the Recover middleware.
// Create a new RecoverConfig
recoverconfig := RecoverConfig{
PrintStack: true,
StackSize: 42,
Output: /* value */,
Handler: /* value */,
}type RecoverConfig struct {
PrintStack bool
StackSize int
Output io.Writer
Handler func(w http.ResponseWriter, r *http.Request, err any)
}| Field | Type | Description |
|---|---|---|
| PrintStack | bool | PrintStack enables printing the stack trace when a panic occurs. Default: true |
| StackSize | int | StackSize is the maximum size of the stack trace buffer. Default: 4KB |
| Output | io.Writer | Output is the writer to output the panic message to. Default: os.Stderr |
| Handler | func(w http.ResponseWriter, r *http.Request, err any) | Handler is a custom function to handle panics. If set, it will be called instead of the default behavior. The handler should write the response and return. |
DefaultRecoverConfig returns the default configuration for Recover.
func DefaultRecoverConfig() RecoverConfigParameters: None
Returns:
RequestIDConfig configures the RequestID middleware.
// Create a new RequestIDConfig
requestidconfig := RequestIDConfig{
Header: "example",
Generator: /* value */,
TargetHeader: "example",
}type RequestIDConfig struct {
Header string
Generator func() string
TargetHeader string
}| Field | Type | Description |
|---|---|---|
| Header | string | Header is the name of the header to read/write the request ID. Default: "X-Request-ID" |
| Generator | func() string | Generator is a function that generates a new request ID. Default: generates a random 16-byte hex string |
| TargetHeader | string | TargetHeader is the header name to set on the response. Default: same as Header |
DefaultRequestIDConfig returns the default configuration for RequestID.
func DefaultRequestIDConfig() RequestIDConfigParameters: None
Returns:
--- Text Output Helpers (Morgan.js style) --- TextOutputOptions configures text output formatting.
// Create a new TextOutputOptions
textoutputoptions := TextOutputOptions{
TimeFormat: "example",
DisableColors: true,
JSONPretty: true,
}type TextOutputOptions struct {
TimeFormat string
DisableColors bool
JSONPretty bool
}| Field | Type | Description |
|---|---|---|
| TimeFormat | string | |
| DisableColors | bool | |
| JSONPretty | bool | for LogFormatJSON |
TimeoutConfig configures the Timeout middleware.
// Create a new TimeoutConfig
timeoutconfig := TimeoutConfig{
Timeout: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
}type TimeoutConfig struct {
Timeout time.Duration
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
}| Field | Type | Description |
|---|---|---|
| Timeout | time.Duration | Timeout is the maximum duration for the request. Default: 30 seconds |
| Handler | http.HandlerFunc | Handler is called when the request times out. If nil, a default 503 Service Unavailable response is sent. |
| SkipFunc | func(r *http.Request) bool | SkipFunc is a function that determines if timeout should be skipped. If it returns true, no timeout is applied. |
DefaultTimeoutConfig returns the default Timeout configuration.
func DefaultTimeoutConfig() TimeoutConfigParameters: None
Returns:
TokenExtractor extracts a custom value from the request.
// Example usage of TokenExtractor
var value TokenExtractor
// Initialize with appropriate valuetype TokenExtractor func(r *http.Request, body []byte) stringContextValueExtractor creates a TokenExtractor for context values.
func ContextValueExtractor(key any) TokenExtractorParameters:
key (any)Returns:
FormValueExtractor creates a TokenExtractor for form fields.
func FormValueExtractor(field string) TokenExtractorParameters:
field (string)Returns:
JSONBodyExtractor creates a TokenExtractor for JSON body fields.
func JSONBodyExtractor(path string) TokenExtractorParameters:
path (string)Returns:
ETagFromContent generates an ETag from content.
func ETagFromContent(content []byte, weak bool) stringParameters:
| Parameter | Type | Description |
|---|---|---|
content | []byte | |
weak | bool |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of ETagFromContent
result := ETagFromContent(/* parameters */)ETagFromString generates an ETag from a string.
func ETagFromString(s string, weak bool) stringParameters:
| Parameter | Type | Description |
|---|---|---|
s | string | |
weak | bool |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of ETagFromString
result := ETagFromString(/* parameters */)ETagFromVersion generates an ETag from a version number.
func ETagFromVersion(version int64, weak bool) stringParameters:
| Parameter | Type | Description |
|---|---|---|
version | int64 | |
weak | bool |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of ETagFromVersion
result := ETagFromVersion(/* parameters */)GetProfiles returns all middleware profiles.
func GetProfiles() map[string]*MiddlewareProfileParameters: None
Returns:
| Type | Description |
|---|---|
map[string]*MiddlewareProfile |
Example:
// Example usage of GetProfiles
result := GetProfiles(/* parameters */)GetRequestID retrieves the request ID from the context. Returns an empty string if no request ID is set.
func GetRequestID(ctx context.Context) stringParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of GetRequestID
result := GetRequestID(/* parameters */)GetRequestIDFromRequest retrieves the request ID from the request context.
func GetRequestIDFromRequest(r *http.Request) stringParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of GetRequestIDFromRequest
result := GetRequestIDFromRequest(/* parameters */)ResetProfiles clears all profiling data.
func ResetProfiles()Parameters: None
Returns: None
Example:
// Example usage of ResetProfiles
result := ResetProfiles(/* parameters */)SetCacheControl sets the Cache-Control header on the response.
func SetCacheControl(w http.ResponseWriter, value string)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
value | string |
Returns: None
Example:
// Example usage of SetCacheControl
result := SetCacheControl(/* parameters */)SetExpires sets the Expires header on the response.
func SetExpires(w http.ResponseWriter, t time.Time)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
t | time.Time |
Returns: None
Example:
// Example usage of SetExpires
result := SetExpires(/* parameters */)SetLastModified sets the Last-Modified header on the response.
func SetLastModified(w http.ResponseWriter, t time.Time)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
t | time.Time |
Returns: None
Example:
// Example usage of SetLastModified
result := SetLastModified(/* parameters */)const RequestIDHeader = "X-Request-ID"// Create a new BasicAuthConfig
basicauthconfig := BasicAuthConfig{
Validator: /* value */,
Realm: "example",
SkipFunc: /* value */,
}type BasicAuthConfig struct {
Validator func(username, password string) bool
Realm string
SkipFunc func(r *http.Request) bool
}// Create a new CORSConfig
corsconfig := CORSConfig{
AllowOrigins: [],
AllowOriginFunc: /* value */,
AllowMethods: [],
AllowHeaders: [],
ExposeHeaders: [],
AllowCredentials: true,
MaxAge: 42,
}type CORSConfig struct {
AllowOrigins []string
AllowOriginFunc func(origin string) bool
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge int
}func DefaultCORSConfig() CORSConfig// Create a new CacheConfig
cacheconfig := CacheConfig{
MaxAge: 42,
SMaxAge: 42,
Public: true,
Private: true,
NoCache: true,
NoStore: true,
NoTransform: true,
MustRevalidate: true,
ProxyRevalidate: true,
Immutable: true,
StaleWhileRevalidate: 42,
StaleIfError: 42,
SkipFunc: /* value */,
VaryHeaders: [],
}type CacheConfig struct {
MaxAge int
SMaxAge int
Public bool
Private bool
NoCache bool
NoStore bool
NoTransform bool
MustRevalidate bool
ProxyRevalidate bool
Immutable bool
StaleWhileRevalidate int
StaleIfError int
SkipFunc func(r *http.Request) bool
VaryHeaders []string
}func DefaultCacheConfig() CacheConfig// Create a new CompressConfig
compressconfig := CompressConfig{
Level: 42,
MinSize: 42,
Types: [],
SkipFunc: /* value */,
}type CompressConfig struct {
Level int
MinSize int
Types []string
SkipFunc func(r *http.Request) bool
}func DefaultCompressConfig() CompressConfig// Create a new ETagConfig
etagconfig := ETagConfig{
Weak: true,
SkipFunc: /* value */,
}type ETagConfig struct {
Weak bool
SkipFunc func(r *http.Request) bool
}func DefaultETagConfig() ETagConfig// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat string// Example usage of LogOutputFunc
var value LogOutputFunc
// Initialize with appropriate valuetype LogOutputFunc func(v LogValues)func TextOutput(w io.Writer, format LogFormat) LogOutputFuncfunc TextOutputCustom(w io.Writer, format string, opts ...TextOutputOptions) LogOutputFuncfunc TextOutputWithOptions(w io.Writer, format LogFormat, opts TextOutputOptions) LogOutputFunc// Create a new LogValues
logvalues := LogValues{
Method: "example",
Path: "example",
URI: "example",
Host: "example",
Protocol: "example",
RemoteIP: "example",
UserAgent: "example",
Referer: "example",
ContentLength: 42,
ContentType: "example",
Status: 42,
ResponseSize: 42,
Latency: /* value */,
Error: error{},
RequestID: "example",
StartTime: /* value */,
Headers: map[],
QueryParams: map[],
FormValues: map[],
CustomFields: map[],
}type LogValues struct {
Method string
Path string
URI string
Host string
Protocol string
RemoteIP string
UserAgent string
Referer string
ContentLength int64
ContentType string
Status int
ResponseSize int
Latency time.Duration
Error error
RequestID string
StartTime time.Time
Headers map[string]string
QueryParams map[string]string
FormValues map[string]string
CustomFields map[string]string
}// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Output: LogOutputFunc{},
Skip: /* value */,
Fields: map[],
CustomTokens: map[],
LogHeaders: [],
LogQueryParams: [],
LogFormValues: [],
CaptureBody: true,
MaxBodySize: 42,
}type LoggerConfig struct {
Output LogOutputFunc
Skip func(r *http.Request) bool
Fields map[string]string
CustomTokens map[string]TokenExtractor
LogHeaders []string
LogQueryParams []string
LogFormValues []string
CaptureBody bool
MaxBodySize int64
}// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware func(next http.Handler) http.Handlerfunc API() []Middlewarefunc APIWithCORS(cors CORSConfig) []Middlewarefunc BasicAuth(username, password string) Middlewarefunc BasicAuthUsers(users map[string]string) Middlewarefunc BasicAuthWithConfig(config BasicAuthConfig) Middlewarefunc BasicAuthWithValidator(validator func(username, password string) bool) Middlewarefunc CORS() Middlewarefunc CORSAllowAll() Middlewarefunc CORSWithConfig(config CORSConfig) Middlewarefunc Cache(maxAge int) Middlewarefunc CacheImmutable(maxAge int) Middlewarefunc CachePrivate(maxAge int) Middlewarefunc CachePublic(maxAge int) Middlewarefunc CacheWithConfig(config CacheConfig) Middlewarefunc Chain(middlewares ...Middleware) Middlewarefunc Compress() Middlewarefunc CompressWithConfig(config CompressConfig) Middlewarefunc CompressWithLevel(level int) Middlewarefunc Development() []Middlewarefunc ETag() Middlewarefunc ETagWeak() Middlewarefunc ETagWithConfig(config ETagConfig) Middlewarefunc Logger() Middlewarefunc LoggerWithConfig(config LoggerConfig) Middlewarefunc Minimal() []Middlewarefunc NoCache() Middlewarefunc Production() []Middlewarefunc ProfileMiddleware(name string, mw Middleware) Middlewarefunc RateLimit(rate float64, burst int) Middlewarefunc RateLimitWithConfig(config RateLimitConfig) Middlewarefunc Recover() Middlewarefunc RecoverWithConfig(config RecoverConfig) Middlewarefunc RequestID() Middlewarefunc RequestIDWithConfig(config RequestIDConfig) Middlewarefunc Secure(rate float64, burst int) []Middlewarefunc Timeout(timeout time.Duration) Middlewarefunc TimeoutWithConfig(config TimeoutConfig) Middlewarefunc Web() []Middleware// Create a new MiddlewareProfile
middlewareprofile := MiddlewareProfile{
Name: "example",
Duration: /* value */,
Allocs: 42,
Bytes: 42,
}type MiddlewareProfile struct {
Name string
Duration time.Duration
Allocs uint64
Bytes uint64
}// Create a new RateLimitConfig
ratelimitconfig := RateLimitConfig{
Rate: 3.14,
Burst: 42,
KeyFunc: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
CleanupInterval: /* value */,
ExpirationTime: /* value */,
}type RateLimitConfig struct {
Rate float64
Burst int
KeyFunc func(r *http.Request) string
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
CleanupInterval time.Duration
ExpirationTime time.Duration
}func DefaultRateLimitConfig() RateLimitConfig// Create a new RecoverConfig
recoverconfig := RecoverConfig{
PrintStack: true,
StackSize: 42,
Output: /* value */,
Handler: /* value */,
}type RecoverConfig struct {
PrintStack bool
StackSize int
Output io.Writer
Handler func(w http.ResponseWriter, r *http.Request, err any)
}func DefaultRecoverConfig() RecoverConfig// Create a new RequestIDConfig
requestidconfig := RequestIDConfig{
Header: "example",
Generator: /* value */,
TargetHeader: "example",
}type RequestIDConfig struct {
Header string
Generator func() string
TargetHeader string
}func DefaultRequestIDConfig() RequestIDConfig// Create a new TextOutputOptions
textoutputoptions := TextOutputOptions{
TimeFormat: "example",
DisableColors: true,
JSONPretty: true,
}type TextOutputOptions struct {
TimeFormat string
DisableColors bool
JSONPretty bool
}// Create a new TimeoutConfig
timeoutconfig := TimeoutConfig{
Timeout: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
}type TimeoutConfig struct {
Timeout time.Duration
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
}func DefaultTimeoutConfig() TimeoutConfig// Example usage of TokenExtractor
var value TokenExtractor
// Initialize with appropriate valuetype TokenExtractor func(r *http.Request, body []byte) stringfunc ContextValueExtractor(key any) TokenExtractorfunc FormValueExtractor(field string) TokenExtractorfunc JSONBodyExtractor(path string) TokenExtractorfunc ETagFromContent(content []byte, weak bool) string// Example usage of ETagFromContent
result := ETagFromContent(/* parameters */)func ETagFromString(s string, weak bool) string// Example usage of ETagFromString
result := ETagFromString(/* parameters */)func ETagFromVersion(version int64, weak bool) string// Example usage of ETagFromVersion
result := ETagFromVersion(/* parameters */)func GetProfiles() map[string]*MiddlewareProfile// Example usage of GetProfiles
result := GetProfiles(/* parameters */)func GetRequestID(ctx context.Context) string// Example usage of GetRequestID
result := GetRequestID(/* parameters */)func GetRequestIDFromRequest(r *http.Request) string// Example usage of GetRequestIDFromRequest
result := GetRequestIDFromRequest(/* parameters */)func ResetProfiles()// Example usage of ResetProfiles
result := ResetProfiles(/* parameters */)func SetCacheControl(w http.ResponseWriter, value string)// Example usage of SetCacheControl
result := SetCacheControl(/* parameters */)func SetExpires(w http.ResponseWriter, t time.Time)// Example usage of SetExpires
result := SetExpires(/* parameters */)func SetLastModified(w http.ResponseWriter, t time.Time)// Example usage of SetLastModified
result := SetLastModified(/* parameters */)const RequestIDHeader = "X-Request-ID"// Create a new BasicAuthConfig
basicauthconfig := BasicAuthConfig{
Validator: /* value */,
Realm: "example",
SkipFunc: /* value */,
}type BasicAuthConfig struct {
Validator func(username, password string) bool
Realm string
SkipFunc func(r *http.Request) bool
}// Create a new CORSConfig
corsconfig := CORSConfig{
AllowOrigins: [],
AllowOriginFunc: /* value */,
AllowMethods: [],
AllowHeaders: [],
ExposeHeaders: [],
AllowCredentials: true,
MaxAge: 42,
}type CORSConfig struct {
AllowOrigins []string
AllowOriginFunc func(origin string) bool
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge int
}func DefaultCORSConfig() CORSConfig// Create a new CacheConfig
cacheconfig := CacheConfig{
MaxAge: 42,
SMaxAge: 42,
Public: true,
Private: true,
NoCache: true,
NoStore: true,
NoTransform: true,
MustRevalidate: true,
ProxyRevalidate: true,
Immutable: true,
StaleWhileRevalidate: 42,
StaleIfError: 42,
SkipFunc: /* value */,
VaryHeaders: [],
}type CacheConfig struct {
MaxAge int
SMaxAge int
Public bool
Private bool
NoCache bool
NoStore bool
NoTransform bool
MustRevalidate bool
ProxyRevalidate bool
Immutable bool
StaleWhileRevalidate int
StaleIfError int
SkipFunc func(r *http.Request) bool
VaryHeaders []string
}func DefaultCacheConfig() CacheConfig// Create a new CompressConfig
compressconfig := CompressConfig{
Level: 42,
MinSize: 42,
Types: [],
SkipFunc: /* value */,
}type CompressConfig struct {
Level int
MinSize int
Types []string
SkipFunc func(r *http.Request) bool
}func DefaultCompressConfig() CompressConfig// Create a new ETagConfig
etagconfig := ETagConfig{
Weak: true,
SkipFunc: /* value */,
}type ETagConfig struct {
Weak bool
SkipFunc func(r *http.Request) bool
}func DefaultETagConfig() ETagConfig// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat string// Example usage of LogOutputFunc
var value LogOutputFunc
// Initialize with appropriate valuetype LogOutputFunc func(v LogValues)func TextOutput(w io.Writer, format LogFormat) LogOutputFuncfunc TextOutputCustom(w io.Writer, format string, opts ...TextOutputOptions) LogOutputFuncfunc TextOutputWithOptions(w io.Writer, format LogFormat, opts TextOutputOptions) LogOutputFunc// Create a new LogValues
logvalues := LogValues{
Method: "example",
Path: "example",
URI: "example",
Host: "example",
Protocol: "example",
RemoteIP: "example",
UserAgent: "example",
Referer: "example",
ContentLength: 42,
ContentType: "example",
Status: 42,
ResponseSize: 42,
Latency: /* value */,
Error: error{},
RequestID: "example",
StartTime: /* value */,
Headers: map[],
QueryParams: map[],
FormValues: map[],
CustomFields: map[],
}type LogValues struct {
Method string
Path string
URI string
Host string
Protocol string
RemoteIP string
UserAgent string
Referer string
ContentLength int64
ContentType string
Status int
ResponseSize int
Latency time.Duration
Error error
RequestID string
StartTime time.Time
Headers map[string]string
QueryParams map[string]string
FormValues map[string]string
CustomFields map[string]string
}// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Output: LogOutputFunc{},
Skip: /* value */,
Fields: map[],
CustomTokens: map[],
LogHeaders: [],
LogQueryParams: [],
LogFormValues: [],
CaptureBody: true,
MaxBodySize: 42,
}type LoggerConfig struct {
Output LogOutputFunc
Skip func(r *http.Request) bool
Fields map[string]string
CustomTokens map[string]TokenExtractor
LogHeaders []string
LogQueryParams []string
LogFormValues []string
CaptureBody bool
MaxBodySize int64
}// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware func(next http.Handler) http.Handlerfunc API() []Middlewarefunc APIWithCORS(cors CORSConfig) []Middlewarefunc BasicAuth(username, password string) Middlewarefunc BasicAuthUsers(users map[string]string) Middlewarefunc BasicAuthWithConfig(config BasicAuthConfig) Middlewarefunc BasicAuthWithValidator(validator func(username, password string) bool) Middlewarefunc CORS() Middlewarefunc CORSAllowAll() Middlewarefunc CORSWithConfig(config CORSConfig) Middlewarefunc Cache(maxAge int) Middlewarefunc CacheImmutable(maxAge int) Middlewarefunc CachePrivate(maxAge int) Middlewarefunc CachePublic(maxAge int) Middlewarefunc CacheWithConfig(config CacheConfig) Middlewarefunc Chain(middlewares ...Middleware) Middlewarefunc Compress() Middlewarefunc CompressWithConfig(config CompressConfig) Middlewarefunc CompressWithLevel(level int) Middlewarefunc Development() []Middlewarefunc ETag() Middlewarefunc ETagWeak() Middlewarefunc ETagWithConfig(config ETagConfig) Middlewarefunc Logger() Middlewarefunc LoggerWithConfig(config LoggerConfig) Middlewarefunc Minimal() []Middlewarefunc NoCache() Middlewarefunc Production() []Middlewarefunc ProfileMiddleware(name string, mw Middleware) Middlewarefunc RateLimit(rate float64, burst int) Middlewarefunc RateLimitWithConfig(config RateLimitConfig) Middlewarefunc Recover() Middlewarefunc RecoverWithConfig(config RecoverConfig) Middlewarefunc RequestID() Middlewarefunc RequestIDWithConfig(config RequestIDConfig) Middlewarefunc Secure(rate float64, burst int) []Middlewarefunc Timeout(timeout time.Duration) Middlewarefunc TimeoutWithConfig(config TimeoutConfig) Middlewarefunc Web() []Middleware// Create a new MiddlewareProfile
middlewareprofile := MiddlewareProfile{
Name: "example",
Duration: /* value */,
Allocs: 42,
Bytes: 42,
}type MiddlewareProfile struct {
Name string
Duration time.Duration
Allocs uint64
Bytes uint64
}// Create a new RateLimitConfig
ratelimitconfig := RateLimitConfig{
Rate: 3.14,
Burst: 42,
KeyFunc: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
CleanupInterval: /* value */,
ExpirationTime: /* value */,
}type RateLimitConfig struct {
Rate float64
Burst int
KeyFunc func(r *http.Request) string
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
CleanupInterval time.Duration
ExpirationTime time.Duration
}func DefaultRateLimitConfig() RateLimitConfig// Create a new RecoverConfig
recoverconfig := RecoverConfig{
PrintStack: true,
StackSize: 42,
Output: /* value */,
Handler: /* value */,
}type RecoverConfig struct {
PrintStack bool
StackSize int
Output io.Writer
Handler func(w http.ResponseWriter, r *http.Request, err any)
}func DefaultRecoverConfig() RecoverConfig// Create a new RequestIDConfig
requestidconfig := RequestIDConfig{
Header: "example",
Generator: /* value */,
TargetHeader: "example",
}type RequestIDConfig struct {
Header string
Generator func() string
TargetHeader string
}func DefaultRequestIDConfig() RequestIDConfig// Create a new TextOutputOptions
textoutputoptions := TextOutputOptions{
TimeFormat: "example",
DisableColors: true,
JSONPretty: true,
}type TextOutputOptions struct {
TimeFormat string
DisableColors bool
JSONPretty bool
}// Create a new TimeoutConfig
timeoutconfig := TimeoutConfig{
Timeout: /* value */,
Handler: /* value */,
SkipFunc: /* value */,
}type TimeoutConfig struct {
Timeout time.Duration
Handler http.HandlerFunc
SkipFunc func(r *http.Request) bool
}func DefaultTimeoutConfig() TimeoutConfig// Example usage of TokenExtractor
var value TokenExtractor
// Initialize with appropriate valuetype TokenExtractor func(r *http.Request, body []byte) stringfunc ContextValueExtractor(key any) TokenExtractorfunc FormValueExtractor(field string) TokenExtractorfunc JSONBodyExtractor(path string) TokenExtractorfunc ETagFromContent(content []byte, weak bool) string// Example usage of ETagFromContent
result := ETagFromContent(/* parameters */)func ETagFromString(s string, weak bool) string// Example usage of ETagFromString
result := ETagFromString(/* parameters */)func ETagFromVersion(version int64, weak bool) string// Example usage of ETagFromVersion
result := ETagFromVersion(/* parameters */)func GetProfiles() map[string]*MiddlewareProfile// Example usage of GetProfiles
result := GetProfiles(/* parameters */)func GetRequestID(ctx context.Context) string// Example usage of GetRequestID
result := GetRequestID(/* parameters */)func GetRequestIDFromRequest(r *http.Request) string// Example usage of GetRequestIDFromRequest
result := GetRequestIDFromRequest(/* parameters */)func ResetProfiles()// Example usage of ResetProfiles
result := ResetProfiles(/* parameters */)func SetCacheControl(w http.ResponseWriter, value string)// Example usage of SetCacheControl
result := SetCacheControl(/* parameters */)func SetExpires(w http.ResponseWriter, t time.Time)// Example usage of SetExpires
result := SetExpires(/* parameters */)func SetLastModified(w http.ResponseWriter, t time.Time)// Example usage of SetLastModified
result := SetLastModified(/* parameters */)