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:
LogEntry represents a JSON log entry.
// Create a new LogEntry
logentry := LogEntry{
Timestamp: "example",
Method: "example",
Path: "example",
URL: "example",
Status: 42,
Latency: "example",
LatencyMs: 3.14,
Size: 42,
RemoteAddr: "example",
UserAgent: "example",
Referer: "example",
RequestID: "example",
Error: "example",
CustomFields: map[],
}type LogEntry struct {
Timestamp string `json:"timestamp"`
Method string `json:"method"`
Path string `json:"path"`
URL string `json:"url,omitempty"`
Status int `json:"status"`
Latency string `json:"latency"`
LatencyMs float64 `json:"latency_ms"`
Size int `json:"size"`
RemoteAddr string `json:"remote_addr"`
UserAgent string `json:"user_agent,omitempty"`
Referer string `json:"referer,omitempty"`
RequestID string `json:"request_id,omitempty"`
Error string `json:"error,omitempty"`
CustomFields map[string]string `json:"custom,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Timestamp | string | |
| Method | string | |
| Path | string | |
| URL | string | |
| Status | int | |
| Latency | string | |
| LatencyMs | float64 | |
| Size | int | |
| RemoteAddr | string | |
| UserAgent | string | |
| Referer | string | |
| RequestID | string | |
| Error | string | |
| CustomFields | map[string]string |
LogFormat represents a predefined log format.
// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat stringLoggerConfig configures the Logger middleware.
// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Format: LogFormat{},
CustomFormat: "example",
Output: /* value */,
Skip: /* value */,
TimeFormat: "example",
Fields: map[],
CustomTokens: map[],
CaptureBody: true,
MaxBodySize: 42,
JSONFields: [],
JSONPretty: true,
DisableColors: true,
}type LoggerConfig struct {
Format LogFormat
CustomFormat string
Output io.Writer
Skip func(r *http.Request) bool
TimeFormat string
Fields map[string]string
CustomTokens map[string]TokenExtractor
CaptureBody bool
MaxBodySize int64
JSONFields []string
JSONPretty bool
DisableColors bool
}| Field | Type | Description |
|---|---|---|
| Format | LogFormat | Format is the log format to use. Default: LogFormatDev |
| CustomFormat | string | CustomFormat is a custom format string using tokens. If set, Format is ignored (unless Format is LogFormatJSON). |
| Output | io.Writer | Output is the writer to output logs to. Default: os.Stdout |
| Skip | func(r *http.Request) bool | Skip is a function that determines if logging should be skipped. If it returns true, the request is not logged. |
| TimeFormat | string | TimeFormat is the time format for the :date token. Default: time.RFC1123 |
| Fields | map[string]string | Fields maps custom field names to their sources. Sources can be: - "header:X-Header-Name" - extracts from request header - "query:param_name" - extracts from query parameter - "cookie:cookie_name" - extracts from cookie Example: {"api_version": "header:X-API-Version", "page": "query:page"} |
| CustomTokens | map[string]TokenExtractor | CustomTokens maps token names to extractor functions. These can extract data from the request body or perform custom logic. Token names should not include the leading colon. Example: {"user_id": func(r, body) string { ... }} |
| CaptureBody | bool | CaptureBody enables capturing the request body for custom token extraction. When enabled, the request body is read and stored for token extractors. Default: false (only enable if you need body-based custom tokens) |
| MaxBodySize | int64 | MaxBodySize is the maximum size of the request body to capture. Default: 64KB |
| JSONFields | []string | JSONFields specifies which fields to include in JSON output. If empty, a default set of fields is used. Fields can be standard tokens (without colon) or custom field names. |
| JSONPretty | bool | JSONPretty enables pretty-printing for JSON output. Default: false |
| DisableColors | bool | DisableColors disables ANSI color codes in output. Default: false |
DefaultLoggerConfig returns the default configuration for Logger.
func DefaultLoggerConfig() LoggerConfigParameters: None
Returns:
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, Logger (JSON format), Recover, and CORS.
func API() []MiddlewareParameters: None
Returns:
APIWithCORS returns a middleware bundle suitable for JSON API servers with a custom CORS configuration. Includes: RequestID, Logger (JSON format), Recover, and CORS with config.
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, Logger (dev format), Recover. This is the same as what helix.Default() uses.
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 that logs HTTP requests. Uses the dev format by default.
func Logger(format LogFormat) MiddlewareParameters:
format (LogFormat)Returns:
LoggerJSON returns a middleware that logs HTTP requests in JSON format.
func LoggerJSON() MiddlewareParameters: None
Returns:
LoggerWithConfig returns a Logger middleware with the given configuration.
func LoggerWithConfig(config LoggerConfig) MiddlewareParameters:
config (LoggerConfig)Returns:
LoggerWithFields returns a Logger middleware with custom fields.
func LoggerWithFields(fields map[string]string) MiddlewareParameters:
fields (map[string]string)Returns:
LoggerWithFormat returns a Logger middleware with a custom format string.
func LoggerWithFormat(format string) MiddlewareParameters:
format (string)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, Logger (combined format), Recover.
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, Logger (JSON format), Recover, RateLimit. 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, Logger (dev format), Recover, and Compress.
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:
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 is a function that extracts a value from the request. It receives the request and the captured request body (if body capture is enabled).
// Example usage of TokenExtractor
var value TokenExtractor
// Initialize with appropriate valuetype TokenExtractor func(r *http.Request, body []byte) stringContextValueExtractor creates a token extractor that extracts a value from request context.
func ContextValueExtractor(key any) TokenExtractorParameters:
key (any)Returns:
FormValueExtractor creates a token extractor that extracts a form field.
func FormValueExtractor(field string) TokenExtractorParameters:
field (string)Returns:
JSONBodyExtractor creates a token extractor that extracts a field from JSON body. The path can be a simple field name like "user_id" or a nested path like "user.id".
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:
LogEntry represents a JSON log entry.
// Create a new LogEntry
logentry := LogEntry{
Timestamp: "example",
Method: "example",
Path: "example",
URL: "example",
Status: 42,
Latency: "example",
LatencyMs: 3.14,
Size: 42,
RemoteAddr: "example",
UserAgent: "example",
Referer: "example",
RequestID: "example",
Error: "example",
CustomFields: map[],
}type LogEntry struct {
Timestamp string `json:"timestamp"`
Method string `json:"method"`
Path string `json:"path"`
URL string `json:"url,omitempty"`
Status int `json:"status"`
Latency string `json:"latency"`
LatencyMs float64 `json:"latency_ms"`
Size int `json:"size"`
RemoteAddr string `json:"remote_addr"`
UserAgent string `json:"user_agent,omitempty"`
Referer string `json:"referer,omitempty"`
RequestID string `json:"request_id,omitempty"`
Error string `json:"error,omitempty"`
CustomFields map[string]string `json:"custom,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Timestamp | string | |
| Method | string | |
| Path | string | |
| URL | string | |
| Status | int | |
| Latency | string | |
| LatencyMs | float64 | |
| Size | int | |
| RemoteAddr | string | |
| UserAgent | string | |
| Referer | string | |
| RequestID | string | |
| Error | string | |
| CustomFields | map[string]string |
LogFormat represents a predefined log format.
// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat stringLoggerConfig configures the Logger middleware.
// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Format: LogFormat{},
CustomFormat: "example",
Output: /* value */,
Skip: /* value */,
TimeFormat: "example",
Fields: map[],
CustomTokens: map[],
CaptureBody: true,
MaxBodySize: 42,
JSONFields: [],
JSONPretty: true,
DisableColors: true,
}type LoggerConfig struct {
Format LogFormat
CustomFormat string
Output io.Writer
Skip func(r *http.Request) bool
TimeFormat string
Fields map[string]string
CustomTokens map[string]TokenExtractor
CaptureBody bool
MaxBodySize int64
JSONFields []string
JSONPretty bool
DisableColors bool
}| Field | Type | Description |
|---|---|---|
| Format | LogFormat | Format is the log format to use. Default: LogFormatDev |
| CustomFormat | string | CustomFormat is a custom format string using tokens. If set, Format is ignored (unless Format is LogFormatJSON). |
| Output | io.Writer | Output is the writer to output logs to. Default: os.Stdout |
| Skip | func(r *http.Request) bool | Skip is a function that determines if logging should be skipped. If it returns true, the request is not logged. |
| TimeFormat | string | TimeFormat is the time format for the :date token. Default: time.RFC1123 |
| Fields | map[string]string | Fields maps custom field names to their sources. Sources can be: - "header:X-Header-Name" - extracts from request header - "query:param_name" - extracts from query parameter - "cookie:cookie_name" - extracts from cookie Example: {"api_version": "header:X-API-Version", "page": "query:page"} |
| CustomTokens | map[string]TokenExtractor | CustomTokens maps token names to extractor functions. These can extract data from the request body or perform custom logic. Token names should not include the leading colon. Example: {"user_id": func(r, body) string { ... }} |
| CaptureBody | bool | CaptureBody enables capturing the request body for custom token extraction. When enabled, the request body is read and stored for token extractors. Default: false (only enable if you need body-based custom tokens) |
| MaxBodySize | int64 | MaxBodySize is the maximum size of the request body to capture. Default: 64KB |
| JSONFields | []string | JSONFields specifies which fields to include in JSON output. If empty, a default set of fields is used. Fields can be standard tokens (without colon) or custom field names. |
| JSONPretty | bool | JSONPretty enables pretty-printing for JSON output. Default: false |
| DisableColors | bool | DisableColors disables ANSI color codes in output. Default: false |
DefaultLoggerConfig returns the default configuration for Logger.
func DefaultLoggerConfig() LoggerConfigParameters: None
Returns:
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, Logger (JSON format), Recover, and CORS.
func API() []MiddlewareParameters: None
Returns:
APIWithCORS returns a middleware bundle suitable for JSON API servers with a custom CORS configuration. Includes: RequestID, Logger (JSON format), Recover, and CORS with config.
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, Logger (dev format), Recover. This is the same as what helix.Default() uses.
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 that logs HTTP requests. Uses the dev format by default.
func Logger(format LogFormat) MiddlewareParameters:
format (LogFormat)Returns:
LoggerJSON returns a middleware that logs HTTP requests in JSON format.
func LoggerJSON() MiddlewareParameters: None
Returns:
LoggerWithConfig returns a Logger middleware with the given configuration.
func LoggerWithConfig(config LoggerConfig) MiddlewareParameters:
config (LoggerConfig)Returns:
LoggerWithFields returns a Logger middleware with custom fields.
func LoggerWithFields(fields map[string]string) MiddlewareParameters:
fields (map[string]string)Returns:
LoggerWithFormat returns a Logger middleware with a custom format string.
func LoggerWithFormat(format string) MiddlewareParameters:
format (string)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, Logger (combined format), Recover.
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, Logger (JSON format), Recover, RateLimit. 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, Logger (dev format), Recover, and Compress.
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:
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 is a function that extracts a value from the request. It receives the request and the captured request body (if body capture is enabled).
// Example usage of TokenExtractor
var value TokenExtractor
// Initialize with appropriate valuetype TokenExtractor func(r *http.Request, body []byte) stringContextValueExtractor creates a token extractor that extracts a value from request context.
func ContextValueExtractor(key any) TokenExtractorParameters:
key (any)Returns:
FormValueExtractor creates a token extractor that extracts a form field.
func FormValueExtractor(field string) TokenExtractorParameters:
field (string)Returns:
JSONBodyExtractor creates a token extractor that extracts a field from JSON body. The path can be a simple field name like "user_id" or a nested path like "user.id".
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// Create a new LogEntry
logentry := LogEntry{
Timestamp: "example",
Method: "example",
Path: "example",
URL: "example",
Status: 42,
Latency: "example",
LatencyMs: 3.14,
Size: 42,
RemoteAddr: "example",
UserAgent: "example",
Referer: "example",
RequestID: "example",
Error: "example",
CustomFields: map[],
}type LogEntry struct {
Timestamp string `json:"timestamp"`
Method string `json:"method"`
Path string `json:"path"`
URL string `json:"url,omitempty"`
Status int `json:"status"`
Latency string `json:"latency"`
LatencyMs float64 `json:"latency_ms"`
Size int `json:"size"`
RemoteAddr string `json:"remote_addr"`
UserAgent string `json:"user_agent,omitempty"`
Referer string `json:"referer,omitempty"`
RequestID string `json:"request_id,omitempty"`
Error string `json:"error,omitempty"`
CustomFields map[string]string `json:"custom,omitempty"`
}// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat string// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Format: LogFormat{},
CustomFormat: "example",
Output: /* value */,
Skip: /* value */,
TimeFormat: "example",
Fields: map[],
CustomTokens: map[],
CaptureBody: true,
MaxBodySize: 42,
JSONFields: [],
JSONPretty: true,
DisableColors: true,
}type LoggerConfig struct {
Format LogFormat
CustomFormat string
Output io.Writer
Skip func(r *http.Request) bool
TimeFormat string
Fields map[string]string
CustomTokens map[string]TokenExtractor
CaptureBody bool
MaxBodySize int64
JSONFields []string
JSONPretty bool
DisableColors bool
}func DefaultLoggerConfig() LoggerConfig// 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(format LogFormat) Middlewarefunc LoggerJSON() Middlewarefunc LoggerWithConfig(config LoggerConfig) Middlewarefunc LoggerWithFields(fields map[string]string) Middlewarefunc LoggerWithFormat(format string) 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 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// Create a new LogEntry
logentry := LogEntry{
Timestamp: "example",
Method: "example",
Path: "example",
URL: "example",
Status: 42,
Latency: "example",
LatencyMs: 3.14,
Size: 42,
RemoteAddr: "example",
UserAgent: "example",
Referer: "example",
RequestID: "example",
Error: "example",
CustomFields: map[],
}type LogEntry struct {
Timestamp string `json:"timestamp"`
Method string `json:"method"`
Path string `json:"path"`
URL string `json:"url,omitempty"`
Status int `json:"status"`
Latency string `json:"latency"`
LatencyMs float64 `json:"latency_ms"`
Size int `json:"size"`
RemoteAddr string `json:"remote_addr"`
UserAgent string `json:"user_agent,omitempty"`
Referer string `json:"referer,omitempty"`
RequestID string `json:"request_id,omitempty"`
Error string `json:"error,omitempty"`
CustomFields map[string]string `json:"custom,omitempty"`
}// Example usage of LogFormat
var value LogFormat
// Initialize with appropriate valuetype LogFormat string// Create a new LoggerConfig
loggerconfig := LoggerConfig{
Format: LogFormat{},
CustomFormat: "example",
Output: /* value */,
Skip: /* value */,
TimeFormat: "example",
Fields: map[],
CustomTokens: map[],
CaptureBody: true,
MaxBodySize: 42,
JSONFields: [],
JSONPretty: true,
DisableColors: true,
}type LoggerConfig struct {
Format LogFormat
CustomFormat string
Output io.Writer
Skip func(r *http.Request) bool
TimeFormat string
Fields map[string]string
CustomTokens map[string]TokenExtractor
CaptureBody bool
MaxBodySize int64
JSONFields []string
JSONPretty bool
DisableColors bool
}func DefaultLoggerConfig() LoggerConfig// 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(format LogFormat) Middlewarefunc LoggerJSON() Middlewarefunc LoggerWithConfig(config LoggerConfig) Middlewarefunc LoggerWithFields(fields map[string]string) Middlewarefunc LoggerWithFormat(format string) 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 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 */)