Documentation
¶
Overview ¶
Package webmiddleware provides reusable web.Middleware helpers for common HTTP concerns such as auth, CORS, compression, timeouts, and request shaping.
Index ¶
- Constants
- Variables
- func AddTrailingSlash() web.Middleware
- func AddTrailingSlashWithConfig(config TrailingSlashConfig) web.Middleware
- func BasicAuth(fn BasicAuthValidator) web.Middleware
- func BasicAuthWithConfig(config BasicAuthConfig) web.Middleware
- func BodyDump(handler BodyDumpHandler) web.Middleware
- func BodyDumpWithConfig(config BodyDumpConfig) web.Middleware
- func BodyLimit(limit string) web.Middleware
- func BodyLimitWithConfig(config BodyLimitConfig) web.Middleware
- func CORS() web.Middleware
- func CORSWithConfig(config CORSConfig) web.Middleware
- func CSRF() web.Middleware
- func CSRFWithConfig(config CSRFConfig) web.Middleware
- func Compress() web.Middleware
- func ContextTimeout(timeout time.Duration) web.Middleware
- func ContextTimeoutWithConfig(config ContextTimeoutConfig) web.Middleware
- func Decompress() web.Middleware
- func DecompressWithConfig(config DecompressConfig) web.Middleware
- func DefaultSkipper(web.Context) bool
- func ErrorBodyDump(handler ErrorBodyDumpHandler) web.Middleware
- func ErrorBodyDumpWithConfig(config ErrorBodyDumpConfig) web.Middleware
- func Gzip() web.Middleware
- func GzipWithConfig(config GzipConfig) web.Middleware
- func HTTPSNonWWWRedirect() web.Middleware
- func HTTPSNonWWWRedirectWithConfig(config RedirectConfig) web.Middleware
- func HTTPSRedirect() web.Middleware
- func HTTPSRedirectWithConfig(config RedirectConfig) web.Middleware
- func HTTPSWWWRedirect() web.Middleware
- func HTTPSWWWRedirectWithConfig(config RedirectConfig) web.Middleware
- func KeyAuth(fn KeyAuthValidator) web.Middleware
- func KeyAuthWithConfig(config KeyAuthConfig) web.Middleware
- func MethodOverride() web.Middleware
- func MethodOverrideWithConfig(config MethodOverrideConfig) web.Middleware
- func NonWWWRedirect() web.Middleware
- func NonWWWRedirectWithConfig(config RedirectConfig) web.Middleware
- func Proxy(balancer ProxyBalancer) web.Middleware
- func ProxyWithConfig(config ProxyConfig) web.Middleware
- func RateLimiter(store RateLimiterStore) web.Middleware
- func RateLimiterWithConfig(config RateLimiterConfig) web.Middleware
- func Recover() web.Middleware
- func RecoverWithConfig(config RecoverConfig) web.Middleware
- func RemoveTrailingSlash() web.Middleware
- func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) web.Middleware
- func RequestID() web.Middleware
- func RequestIDWithConfig(config RequestIDConfig) web.Middleware
- func RequestLoggerWithConfig(config RequestLoggerConfig) web.Middleware
- func Rewrite(rules map[string]string) web.Middleware
- func RewriteWithConfig(config RewriteConfig) web.Middleware
- func Secure() web.Middleware
- func SecureWithConfig(config SecureConfig) web.Middleware
- func Static(root string) web.Middleware
- func StaticWithConfig(config StaticConfig) web.Middleware
- func Timeout() web.Middleware
- func TimeoutWithConfig(config TimeoutConfig) web.Middleware
- func WWWRedirect() web.Middleware
- func WWWRedirectWithConfig(config RedirectConfig) web.Middleware
- type BasicAuthConfig
- type BasicAuthValidator
- type BodyDumpConfig
- type BodyDumpHandler
- type BodyLimitConfig
- type CORSConfig
- type CSRFConfig
- type CSRFErrorHandler
- type ContextTimeoutConfig
- type DecompressConfig
- type Decompressor
- type DefaultGzipDecompressPool
- type ErrKeyAuthMissing
- type ErrorBodyDumpConfig
- type ErrorBodyDumpHandler
- type Extractor
- type GzipConfig
- type KeyAuthConfig
- type KeyAuthErrorHandler
- type KeyAuthValidator
- type MethodOverrideConfig
- type MethodOverrideGetter
- type ProxyBalancer
- type ProxyConfig
- type ProxyTarget
- type RateLimiterConfig
- type RateLimiterMemoryStore
- type RateLimiterMemoryStoreConfig
- type RateLimiterStore
- type RecoverConfig
- type RedirectConfig
- type RequestIDConfig
- type RequestLoggerConfig
- type RequestLoggerValues
- type RewriteConfig
- type SecureConfig
- type Skipper
- type StaticConfig
- type TimeoutConfig
- type TrailingSlashConfig
- type ValuesExtractor
Constants ¶
const (
// GZIPEncoding is the gzip content-encoding value.
GZIPEncoding = "gzip"
)
Variables ¶
var ( // ErrRateLimitExceeded is returned when the rate limit is exceeded. ErrRateLimitExceeded = errors.New("rate limit exceeded") // ErrRateLimitIdentifier is returned when extracting a rate limit identifier fails. ErrRateLimitIdentifier = errors.New("error while extracting identifier") )
var DefaultBasicAuthConfig = BasicAuthConfig{
Realm: defaultAuthRealm,
}
DefaultBasicAuthConfig is the default basic auth middleware config.
var DefaultBodyDumpConfig = BodyDumpConfig{ Skipper: DefaultSkipper, }
DefaultBodyDumpConfig is the default body dump config.
var DefaultCORSConfig = CORSConfig{ AllowOrigins: []string{"*"}, AllowMethods: []string{ http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete, }, }
DefaultCORSConfig is the default CORS middleware config.
var DefaultCSRFConfig = CSRFConfig{ Skipper: DefaultSkipper, TokenLength: 32, TokenLookup: "header:X-CSRF-Token", ContextKey: "csrf", CookieName: "_csrf", CookieMaxAge: 86400, CookieSameSite: http.SameSiteDefaultMode, }
DefaultCSRFConfig is the default CSRF config.
var DefaultDecompressConfig = DecompressConfig{ Skipper: DefaultSkipper, GzipDecompressPool: &DefaultGzipDecompressPool{}, }
DefaultDecompressConfig is the default decompress config.
var DefaultErrorBodyDumpConfig = ErrorBodyDumpConfig{ Skipper: DefaultSkipper, }
DefaultErrorBodyDumpConfig is the default config.
var DefaultGzipConfig = GzipConfig{ Skipper: DefaultSkipper, Level: -1, MinLength: 0, }
DefaultGzipConfig is the default gzip config.
var DefaultKeyAuthConfig = KeyAuthConfig{
KeyLookup: "header:Authorization",
AuthScheme: "Bearer",
}
DefaultKeyAuthConfig is the default key auth middleware config.
var DefaultMethodOverrideConfig = MethodOverrideConfig{ Getter: MethodFromHeader("X-HTTP-Method-Override"), }
DefaultMethodOverrideConfig is the default method override config.
var DefaultProxyConfig = ProxyConfig{ Skipper: DefaultSkipper, ContextKey: "target", }
DefaultProxyConfig is the default proxy config.
var DefaultRateLimiterConfig = RateLimiterConfig{ Skipper: DefaultSkipper, IdentifierExtractor: func(r web.Context) (string, error) { return r.RealIP(), nil }, ErrorHandler: func(r web.Context, err error) error { return r.JSON(403, map[string]any{ "error": ErrRateLimitIdentifier.Error(), }) }, DenyHandler: func(r web.Context, _ string, err error) error { return r.JSON(429, map[string]any{ "error": ErrRateLimitExceeded.Error(), }) }, }
DefaultRateLimiterConfig is the default rate limiter config.
var DefaultRateLimiterMemoryStoreConfig = RateLimiterMemoryStoreConfig{ ExpiresIn: 3 * time.Minute, }
DefaultRateLimiterMemoryStoreConfig is the default in-memory store config.
var DefaultRecoverConfig = RecoverConfig{
StackSize: 4 << 10,
}
DefaultRecoverConfig is the default Recover middleware config.
var DefaultRedirectConfig = RedirectConfig{ Code: http.StatusMovedPermanently, }
DefaultRedirectConfig is the default redirect config.
var DefaultRequestIDConfig = RequestIDConfig{
Generator: defaultRequestIDGenerator,
TargetHeader: "X-Request-ID",
ContextKey: "request_id",
}
DefaultRequestIDConfig is the default RequestID middleware config.
var DefaultRewriteConfig = RewriteConfig{}
DefaultRewriteConfig is the default rewrite config.
var DefaultSecureConfig = SecureConfig{ Skipper: DefaultSkipper, XSSProtection: "1; mode=block", ContentTypeNosniff: "nosniff", XFrameOptions: "SAMEORIGIN", }
DefaultSecureConfig is the default secure middleware config.
var DefaultStaticConfig = StaticConfig{ Skipper: DefaultSkipper, Index: "index.html", }
DefaultStaticConfig is the default static config.
var DefaultTimeoutConfig = TimeoutConfig{ Skipper: DefaultSkipper, ErrorMessage: "", }
DefaultTimeoutConfig is the default timeout config.
var DefaultTrailingSlashConfig = TrailingSlashConfig{}
DefaultTrailingSlashConfig is the default trailing slash config.
Functions ¶
func AddTrailingSlash ¶
func AddTrailingSlash() web.Middleware
AddTrailingSlash adds a trailing slash to the request path. @group Middleware - Path Rewriting Example: router := echoweb.New().Router() router.Use(webmiddleware.AddTrailingSlash())
router.GET("/docs/", func(c web.Context) error {
return c.Text(200, "docs")
})
func AddTrailingSlashWithConfig ¶
func AddTrailingSlashWithConfig(config TrailingSlashConfig) web.Middleware
AddTrailingSlashWithConfig returns trailing-slash middleware with config. @group Middleware - Path Rewriting Example: router := echoweb.New().Router()
router.Use(webmiddleware.AddTrailingSlashWithConfig(webmiddleware.TrailingSlashConfig{
RedirectCode: 308,
}))
router.GET("/docs/", func(c web.Context) error {
return c.Text(200, "docs")
})
func BasicAuth ¶
func BasicAuth(fn BasicAuthValidator) web.Middleware
BasicAuth returns basic auth middleware. @group Middleware - Auth Example: router := echoweb.New().Router()
router.Use(webmiddleware.BasicAuth(func(user, pass string, c web.Context) (bool, error) {
return user == "demo" && pass == "secret", nil
}))
router.GET("/admin", func(c web.Context) error {
return c.Text(200, "welcome")
})
func BasicAuthWithConfig ¶
func BasicAuthWithConfig(config BasicAuthConfig) web.Middleware
BasicAuthWithConfig returns basic auth middleware with config. @group Middleware - Auth Example: router := echoweb.New().Router()
router.Use(webmiddleware.BasicAuthWithConfig(webmiddleware.BasicAuthConfig{
Realm: "Admin",
Validator: func(user, pass string, c web.Context) (bool, error) {
return user == "demo" && pass == "secret", nil
},
}))
router.GET("/admin", func(c web.Context) error {
return c.Text(200, "welcome")
})
func BodyDump ¶
func BodyDump(handler BodyDumpHandler) web.Middleware
BodyDump captures request and response payloads. @group Middleware - Payloads Example: router := echoweb.New().Router()
router.Use(webmiddleware.BodyDump(func(c web.Context, reqBody, resBody []byte) {
log.Printf("%s %s -> %d bytes", c.Method(), c.URI(), len(resBody))
}))
router.POST("/webhooks", func(c web.Context) error {
return c.JSON(202, map[string]any{"queued": true})
})
func BodyDumpWithConfig ¶
func BodyDumpWithConfig(config BodyDumpConfig) web.Middleware
BodyDumpWithConfig captures request and response payloads with config. @group Middleware - Payloads Example: router := echoweb.New().Router()
router.Use(webmiddleware.BodyDumpWithConfig(webmiddleware.BodyDumpConfig{
Skipper: func(c web.Context) bool {
return c.Path() == "/healthz"
},
Handler: func(c web.Context, reqBody, resBody []byte) {
log.Printf("%s %s -> %d bytes", c.Method(), c.URI(), len(resBody))
},
}))
func BodyLimit ¶
func BodyLimit(limit string) web.Middleware
BodyLimit returns middleware that limits request body size. @group Middleware - Payloads Example: router := echoweb.New().Router() router.Use(webmiddleware.BodyLimit("2MB"))
router.POST("/uploads", func(c web.Context) error {
return c.NoContent(204)
})
func BodyLimitWithConfig ¶
func BodyLimitWithConfig(config BodyLimitConfig) web.Middleware
BodyLimitWithConfig returns body limit middleware with config. @group Middleware - Payloads Example: router := echoweb.New().Router()
router.Use(webmiddleware.BodyLimitWithConfig(webmiddleware.BodyLimitConfig{
Limit: "10MB",
}))
router.POST("/imports", func(c web.Context) error {
return c.NoContent(202)
})
func CORS ¶
func CORS() web.Middleware
CORS returns Cross-Origin Resource Sharing middleware. @group Middleware - Security Example: router := echoweb.New().Router() router.Use(webmiddleware.CORS())
router.GET("/api/healthz", func(c web.Context) error {
return c.JSON(200, map[string]any{"ok": true})
})
func CORSWithConfig ¶
func CORSWithConfig(config CORSConfig) web.Middleware
CORSWithConfig returns CORS middleware with config. @group Middleware - Security Example: router := echoweb.New().Router()
router.Use(webmiddleware.CORSWithConfig(webmiddleware.CORSConfig{
AllowOrigins: []string{"https://app.example.com"},
AllowMethods: []string{"GET", "POST", "PATCH"},
}))
router.GET("/api/healthz", func(c web.Context) error {
return c.JSON(200, map[string]any{"ok": true})
})
func CSRF ¶
func CSRF() web.Middleware
CSRF enables token-based CSRF protection. @group Middleware - Auth Example: router := echoweb.New().Router() router.Use(webmiddleware.CSRF())
router.POST("/settings", func(c web.Context) error {
return c.NoContent(204)
})
func CSRFWithConfig ¶
func CSRFWithConfig(config CSRFConfig) web.Middleware
CSRFWithConfig enables token-based CSRF protection with config. @group Middleware - Auth Example: router := echoweb.New().Router()
router.Use(webmiddleware.CSRFWithConfig(webmiddleware.CSRFConfig{
CookieName: "_csrf",
TokenLookup: "header:X-CSRF-Token",
}))
router.POST("/settings", func(c web.Context) error {
return c.NoContent(204)
})
func Compress ¶
func Compress() web.Middleware
Compress enables gzip response compression for clients that support it. @group Middleware - Compression Example: router := echoweb.New().Router() router.Use(webmiddleware.Compress())
router.GET("/reports", func(c web.Context) error {
return c.Text(200, "large report response")
})
func ContextTimeout ¶
func ContextTimeout(timeout time.Duration) web.Middleware
ContextTimeout sets a timeout on the request context. @group Middleware - Request Lifecycle Example: router := echoweb.New().Router() router.Use(webmiddleware.ContextTimeout(2 * time.Second))
router.GET("/reports", func(c web.Context) error {
return c.JSON(200, map[string]any{"ready": true})
})
func ContextTimeoutWithConfig ¶
func ContextTimeoutWithConfig(config ContextTimeoutConfig) web.Middleware
ContextTimeoutWithConfig sets a timeout on the request context with config. @group Middleware - Request Lifecycle Example: router := echoweb.New().Router()
router.Use(webmiddleware.ContextTimeoutWithConfig(webmiddleware.ContextTimeoutConfig{
Timeout: time.Second,
}))
func Decompress ¶
func Decompress() web.Middleware
Decompress inflates gzip-encoded request bodies before handlers read them. @group Middleware - Compression Example: router := echoweb.New().Router() router.Use(webmiddleware.Decompress())
router.POST("/ingest", func(c web.Context) error {
data, _ := io.ReadAll(c.Request().Body)
return c.JSON(200, map[string]int{"bytes": len(data)})
})
func DecompressWithConfig ¶
func DecompressWithConfig(config DecompressConfig) web.Middleware
DecompressWithConfig inflates gzip-encoded request bodies with custom options. @group Middleware - Compression Example: router := echoweb.New().Router()
router.Use(webmiddleware.DecompressWithConfig(webmiddleware.DecompressConfig{
Skipper: func(c web.Context) bool {
return c.Path() == "/webhooks/raw"
},
}))
router.POST("/ingest", func(c web.Context) error {
return c.NoContent(202)
})
func DefaultSkipper ¶
DefaultSkipper always runs the middleware. @group Middleware - Request Lifecycle Example: fmt.Println(webmiddleware.DefaultSkipper(nil))
// false
func ErrorBodyDump ¶
func ErrorBodyDump(handler ErrorBodyDumpHandler) web.Middleware
ErrorBodyDump captures response bodies for non-2xx and non-3xx responses. @group Middleware - Payloads Example: router := echoweb.New().Router()
router.Use(webmiddleware.ErrorBodyDump(func(c web.Context, status int, body []byte) {
log.Printf("%s %s failed with %d", c.Method(), c.URI(), status)
}))
router.GET("/reports/:id", func(c web.Context) error {
return c.Text(404, "report not found")
})
func ErrorBodyDumpWithConfig ¶
func ErrorBodyDumpWithConfig(config ErrorBodyDumpConfig) web.Middleware
ErrorBodyDumpWithConfig captures response bodies for non-success responses with config. @group Middleware - Payloads Example: router := echoweb.New().Router()
router.Use(webmiddleware.ErrorBodyDumpWithConfig(webmiddleware.ErrorBodyDumpConfig{
Skipper: func(c web.Context) bool {
return c.Path() == "/healthz"
},
Handler: func(c web.Context, status int, body []byte) {
log.Printf("%s %s failed with %d", c.Method(), c.URI(), status)
},
}))
func Gzip ¶
func Gzip() web.Middleware
Gzip enables gzip response compression for clients that support it. @group Middleware - Compression Example: router := echoweb.New().Router()
router.GET("/feed", func(c web.Context) error {
return c.Text(200, "large feed response")
}, webmiddleware.Gzip())
func GzipWithConfig ¶
func GzipWithConfig(config GzipConfig) web.Middleware
GzipWithConfig enables gzip response compression with custom options. @group Middleware - Compression Example: router := echoweb.New().Router()
router.Use(webmiddleware.GzipWithConfig(webmiddleware.GzipConfig{
MinLength: 1024,
}))
func HTTPSNonWWWRedirect ¶
func HTTPSNonWWWRedirect() web.Middleware
HTTPSNonWWWRedirect redirects to https without www. @group Middleware - Redirects Example: router := echoweb.New().Router() router.Use(webmiddleware.HTTPSNonWWWRedirect())
func HTTPSNonWWWRedirectWithConfig ¶
func HTTPSNonWWWRedirectWithConfig(config RedirectConfig) web.Middleware
HTTPSNonWWWRedirectWithConfig returns HTTPS non-WWW redirect middleware with config. @group Middleware - Redirects Example: router := echoweb.New().Router()
router.Use(webmiddleware.HTTPSNonWWWRedirectWithConfig(webmiddleware.RedirectConfig{
Code: 307,
}))
func HTTPSRedirect ¶
func HTTPSRedirect() web.Middleware
HTTPSRedirect redirects http requests to https. @group Middleware - Redirects Example: router := echoweb.New().Router() router.Use(webmiddleware.HTTPSRedirect())
router.GET("/docs", func(c web.Context) error {
return c.Text(200, "docs")
})
func HTTPSRedirectWithConfig ¶
func HTTPSRedirectWithConfig(config RedirectConfig) web.Middleware
HTTPSRedirectWithConfig returns HTTPS redirect middleware with config. @group Middleware - Redirects Example: router := echoweb.New().Router()
router.Use(webmiddleware.HTTPSRedirectWithConfig(webmiddleware.RedirectConfig{
Code: 307,
}))
func HTTPSWWWRedirect ¶
func HTTPSWWWRedirect() web.Middleware
HTTPSWWWRedirect redirects to https + www. @group Middleware - Redirects Example: router := echoweb.New().Router() router.Use(webmiddleware.HTTPSWWWRedirect())
func HTTPSWWWRedirectWithConfig ¶
func HTTPSWWWRedirectWithConfig(config RedirectConfig) web.Middleware
HTTPSWWWRedirectWithConfig returns HTTPS+WWW redirect middleware with config. @group Middleware - Redirects Example: router := echoweb.New().Router()
router.Use(webmiddleware.HTTPSWWWRedirectWithConfig(webmiddleware.RedirectConfig{
Code: 307,
}))
func KeyAuth ¶
func KeyAuth(fn KeyAuthValidator) web.Middleware
KeyAuth returns key auth middleware. @group Middleware - Auth Example: router := echoweb.New().Router()
router.Use(webmiddleware.KeyAuth(func(key string, c web.Context) (bool, error) {
return key == "demo-key", nil
}))
router.GET("/api/reports", func(c web.Context) error {
return c.JSON(200, map[string]any{"ready": true})
})
func KeyAuthWithConfig ¶
func KeyAuthWithConfig(config KeyAuthConfig) web.Middleware
KeyAuthWithConfig returns key auth middleware with config. @group Middleware - Auth Example: router := echoweb.New().Router()
router.Use(webmiddleware.KeyAuthWithConfig(webmiddleware.KeyAuthConfig{
KeyLookup: "query:api_key",
Validator: func(key string, c web.Context) (bool, error) {
return key == "demo-key", nil
},
}))
router.GET("/api/reports", func(c web.Context) error {
return c.JSON(200, map[string]any{"ready": true})
})
func MethodOverride ¶
func MethodOverride() web.Middleware
MethodOverride returns method override middleware. @group Middleware - Method Override Example: router := echoweb.New().Router() router.Use(webmiddleware.MethodOverride())
router.PATCH("/articles/:id", func(c web.Context) error {
return c.NoContent(204)
})
func MethodOverrideWithConfig ¶
func MethodOverrideWithConfig(config MethodOverrideConfig) web.Middleware
MethodOverrideWithConfig returns method override middleware with config. @group Middleware - Method Override Example: router := echoweb.New().Router()
router.Use(webmiddleware.MethodOverrideWithConfig(webmiddleware.MethodOverrideConfig{
Getter: webmiddleware.MethodFromQuery("_method"),
}))
router.DELETE("/articles/:id", func(c web.Context) error {
return c.NoContent(204)
})
func NonWWWRedirect ¶
func NonWWWRedirect() web.Middleware
NonWWWRedirect redirects to the non-www host. @group Middleware - Redirects Example: router := echoweb.New().Router() router.Use(webmiddleware.NonWWWRedirect())
func NonWWWRedirectWithConfig ¶
func NonWWWRedirectWithConfig(config RedirectConfig) web.Middleware
NonWWWRedirectWithConfig returns non-WWW redirect middleware with config. @group Middleware - Redirects Example: router := echoweb.New().Router()
router.Use(webmiddleware.NonWWWRedirectWithConfig(webmiddleware.RedirectConfig{
Code: 307,
}))
func Proxy ¶
func Proxy(balancer ProxyBalancer) web.Middleware
Proxy creates a proxy middleware. @group Middleware - Proxying Example: target, _ := url.Parse("http://localhost:8080") balancer := webmiddleware.NewRandomBalancer([]*webmiddleware.ProxyTarget{{URL: target}})
router := echoweb.New().Router() router.Use(webmiddleware.Proxy(balancer))
func ProxyWithConfig ¶
func ProxyWithConfig(config ProxyConfig) web.Middleware
ProxyWithConfig creates a proxy middleware with config. @group Middleware - Proxying Example: target, _ := url.Parse("http://localhost:8080") balancer := webmiddleware.NewRoundRobinBalancer([]*webmiddleware.ProxyTarget{{URL: target}})
router := echoweb.New().Router()
router.Use(webmiddleware.ProxyWithConfig(webmiddleware.ProxyConfig{
Balancer: balancer,
Rewrite: map[string]string{
"/api/*": "/$1",
},
}))
func RateLimiter ¶
func RateLimiter(store RateLimiterStore) web.Middleware
RateLimiter creates a rate limiting middleware. @group Middleware - Rate Limiting Example: store := webmiddleware.NewRateLimiterMemoryStore(rate.Every(time.Second))
router := echoweb.New().Router() router.Use(webmiddleware.RateLimiter(store))
router.POST("/api/messages", func(c web.Context) error {
return c.NoContent(202)
})
func RateLimiterWithConfig ¶
func RateLimiterWithConfig(config RateLimiterConfig) web.Middleware
RateLimiterWithConfig creates a rate limiting middleware with config. @group Middleware - Rate Limiting Example: store := webmiddleware.NewRateLimiterMemoryStore(rate.Every(time.Second))
router := echoweb.New().Router()
router.Use(webmiddleware.RateLimiterWithConfig(webmiddleware.RateLimiterConfig{
Store: store,
IdentifierExtractor: func(c web.Context) (string, error) {
return c.Header("X-Account-ID"), nil
},
}))
func Recover ¶
func Recover() web.Middleware
Recover returns middleware that recovers panics from the handler chain. @group Middleware - Reliability Example: router := echoweb.New().Router() router.Use(webmiddleware.Recover())
router.GET("/panic", func(c web.Context) error {
panic("boom")
})
func RecoverWithConfig ¶
func RecoverWithConfig(config RecoverConfig) web.Middleware
RecoverWithConfig returns recover middleware with config. @group Middleware - Reliability Example: router := echoweb.New().Router()
router.Use(webmiddleware.RecoverWithConfig(webmiddleware.RecoverConfig{
DisableStack: true,
HandleError: func(c web.Context, err error, stack []byte) error {
return c.JSON(500, map[string]any{"error": "internal server error"})
},
}))
func RemoveTrailingSlash ¶
func RemoveTrailingSlash() web.Middleware
RemoveTrailingSlash removes the trailing slash from the request path. @group Middleware - Path Rewriting Example: router := echoweb.New().Router() router.Use(webmiddleware.RemoveTrailingSlash())
router.GET("/docs", func(c web.Context) error {
return c.Text(200, "docs")
})
func RemoveTrailingSlashWithConfig ¶
func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) web.Middleware
RemoveTrailingSlashWithConfig returns remove-trailing-slash middleware with config. @group Middleware - Path Rewriting Example: router := echoweb.New().Router()
router.Use(webmiddleware.RemoveTrailingSlashWithConfig(webmiddleware.TrailingSlashConfig{
RedirectCode: 308,
}))
router.GET("/docs", func(c web.Context) error {
return c.Text(200, "docs")
})
func RequestID ¶
func RequestID() web.Middleware
RequestID returns middleware that sets a request id header and context value. @group Middleware - Request Lifecycle Example: router := echoweb.New().Router() router.Use(webmiddleware.RequestID())
router.GET("/healthz", func(c web.Context) error {
return c.JSON(200, map[string]any{
"request_id": c.Get("request_id"),
})
})
func RequestIDWithConfig ¶
func RequestIDWithConfig(config RequestIDConfig) web.Middleware
RequestIDWithConfig returns RequestID middleware with config. @group Middleware - Request Lifecycle Example: router := echoweb.New().Router()
router.Use(webmiddleware.RequestIDWithConfig(webmiddleware.RequestIDConfig{
TargetHeader: "X-Correlation-ID",
ContextKey: "correlation_id",
}))
func RequestLoggerWithConfig ¶
func RequestLoggerWithConfig(config RequestLoggerConfig) web.Middleware
RequestLoggerWithConfig returns request logger middleware with config. @group Middleware - Request Lifecycle Example: router := echoweb.New().Router()
router.Use(webmiddleware.RequestLoggerWithConfig(webmiddleware.RequestLoggerConfig{
LogValuesFunc: func(c web.Context, values webmiddleware.RequestLoggerValues) error {
log.Printf("%s %s %d %s", values.Method, values.URI, values.Status, values.Latency)
return nil
},
}))
router.GET("/users/:id", func(c web.Context) error {
return c.NoContent(204)
})
func Rewrite ¶
func Rewrite(rules map[string]string) web.Middleware
Rewrite rewrites the request path using wildcard rules. @group Middleware - Path Rewriting Example: router := echoweb.New().Router()
router.Use(webmiddleware.Rewrite(map[string]string{
"/old/*": "/new/$1",
}))
router.GET("/new/:name", func(c web.Context) error {
return c.Text(200, c.Param("name"))
})
func RewriteWithConfig ¶
func RewriteWithConfig(config RewriteConfig) web.Middleware
RewriteWithConfig rewrites the request path using wildcard and regex rules. @group Middleware - Path Rewriting Example: router := echoweb.New().Router()
router.Use(webmiddleware.RewriteWithConfig(webmiddleware.RewriteConfig{
Rules: map[string]string{"/old/*": "/v2/$1"},
}))
router.GET("/v2/:name", func(c web.Context) error {
return c.Text(200, c.Param("name"))
})
func Secure ¶
func Secure() web.Middleware
Secure sets security-oriented response headers. @group Middleware - Security Example: router := echoweb.New().Router() router.Use(webmiddleware.Secure())
router.GET("/", func(c web.Context) error {
return c.Text(200, "home")
})
func SecureWithConfig ¶
func SecureWithConfig(config SecureConfig) web.Middleware
SecureWithConfig sets security-oriented response headers with config. @group Middleware - Security Example: router := echoweb.New().Router()
router.Use(webmiddleware.SecureWithConfig(webmiddleware.SecureConfig{
ReferrerPolicy: "same-origin",
ContentSecurityPolicy: "default-src 'self'",
}))
func Static ¶
func Static(root string) web.Middleware
Static serves static content from the provided root. @group Middleware - Static Files Example: router := echoweb.New().Router() router.Use(webmiddleware.Static("public"))
router.GET("/healthz", func(c web.Context) error {
return c.NoContent(204)
})
func StaticWithConfig ¶
func StaticWithConfig(config StaticConfig) web.Middleware
StaticWithConfig serves static content using config. @group Middleware - Static Files Example: router := echoweb.New().Router()
router.Use(webmiddleware.StaticWithConfig(webmiddleware.StaticConfig{
Root: "public",
HTML5: true,
}))
func Timeout ¶
func Timeout() web.Middleware
Timeout returns a response-timeout middleware. @group Middleware - Request Lifecycle Example: router := echoweb.New().Router() router.Use(webmiddleware.Timeout())
router.GET("/healthz", func(c web.Context) error {
return c.NoContent(204)
})
func TimeoutWithConfig ¶
func TimeoutWithConfig(config TimeoutConfig) web.Middleware
TimeoutWithConfig returns a response-timeout middleware with config. @group Middleware - Request Lifecycle Example: router := echoweb.New().Router()
router.Use(webmiddleware.TimeoutWithConfig(webmiddleware.TimeoutConfig{
Timeout: time.Second,
ErrorMessage: "request timed out",
}))
func WWWRedirect ¶
func WWWRedirect() web.Middleware
WWWRedirect redirects to the www host. @group Middleware - Redirects Example: router := echoweb.New().Router() router.Use(webmiddleware.WWWRedirect())
func WWWRedirectWithConfig ¶
func WWWRedirectWithConfig(config RedirectConfig) web.Middleware
WWWRedirectWithConfig returns WWW redirect middleware with config. @group Middleware - Redirects Example: router := echoweb.New().Router()
router.Use(webmiddleware.WWWRedirectWithConfig(webmiddleware.RedirectConfig{
Code: 307,
}))
Types ¶
type BasicAuthConfig ¶
type BasicAuthConfig struct {
Validator BasicAuthValidator
Realm string
}
BasicAuthConfig configures basic auth middleware.
type BasicAuthValidator ¶
BasicAuthValidator validates a username/password pair.
type BodyDumpConfig ¶
type BodyDumpConfig struct {
Skipper Skipper
Handler BodyDumpHandler
}
BodyDumpConfig configures request/response body dumping.
type BodyDumpHandler ¶
BodyDumpHandler receives the request and response payload.
type BodyLimitConfig ¶
type BodyLimitConfig struct {
Limit string
}
BodyLimitConfig configures body limit middleware.
type CORSConfig ¶
type CORSConfig struct {
AllowOrigins []string
AllowOriginFunc func(origin string) (bool, error)
AllowMethods []string
AllowHeaders []string
AllowCredentials bool
ExposeHeaders []string
MaxAge int
}
CORSConfig configures CORS middleware.
type CSRFConfig ¶
type CSRFConfig struct {
Skipper Skipper
TokenLength uint8
TokenLookup string
ContextKey string
CookieName string
CookieDomain string
CookiePath string
CookieMaxAge int
CookieSecure bool
CookieHTTPOnly bool
CookieSameSite http.SameSite
ErrorHandler CSRFErrorHandler
// contains filtered or unexported fields
}
CSRFConfig configures CSRF protection.
type CSRFErrorHandler ¶
CSRFErrorHandler handles CSRF failures.
type ContextTimeoutConfig ¶
type ContextTimeoutConfig struct {
Skipper Skipper
ErrorHandler func(error, web.Context) error
Timeout time.Duration
}
ContextTimeoutConfig configures request context timeouts.
type DecompressConfig ¶
type DecompressConfig struct {
Skipper Skipper
GzipDecompressPool Decompressor
}
DecompressConfig configures request decompression.
type Decompressor ¶
type Decompressor interface {
// contains filtered or unexported methods
}
Decompressor provides a pool of gzip readers.
type DefaultGzipDecompressPool ¶
type DefaultGzipDecompressPool struct{}
DefaultGzipDecompressPool is the default gzip reader pool.
type ErrKeyAuthMissing ¶
type ErrKeyAuthMissing struct {
Err error
}
ErrKeyAuthMissing is returned when no key can be extracted.
func (*ErrKeyAuthMissing) Error ¶
func (e *ErrKeyAuthMissing) Error() string
Error reports that the configured key auth extractor could not find credentials.
func (*ErrKeyAuthMissing) Unwrap ¶
func (e *ErrKeyAuthMissing) Unwrap() error
Unwrap returns the underlying cause for a missing key auth credential.
type ErrorBodyDumpConfig ¶
type ErrorBodyDumpConfig struct {
Skipper Skipper
Handler ErrorBodyDumpHandler
}
ErrorBodyDumpConfig configures non-success response body capture.
type ErrorBodyDumpHandler ¶
ErrorBodyDumpHandler receives non-success response bodies.
type GzipConfig ¶
GzipConfig configures gzip compression.
type KeyAuthConfig ¶
type KeyAuthConfig struct {
KeyLookup string
AuthScheme string
Validator KeyAuthValidator
ErrorHandler KeyAuthErrorHandler
ContinueOnIgnoredError bool
}
KeyAuthConfig configures key auth middleware.
type KeyAuthErrorHandler ¶
KeyAuthErrorHandler handles missing/invalid auth keys.
type KeyAuthValidator ¶
KeyAuthValidator validates an extracted auth key.
type MethodOverrideConfig ¶
type MethodOverrideConfig struct {
Getter MethodOverrideGetter
}
MethodOverrideConfig configures method override middleware.
type MethodOverrideGetter ¶
MethodOverrideGetter gets an override method from the request.
func MethodFromForm ¶
func MethodFromForm(param string) MethodOverrideGetter
MethodFromForm gets an override method from a form field. @group Middleware - Method Override Example: router := echoweb.New().Router()
router.Use(webmiddleware.MethodOverrideWithConfig(webmiddleware.MethodOverrideConfig{
Getter: webmiddleware.MethodFromForm("_method"),
}))
func MethodFromHeader ¶
func MethodFromHeader(header string) MethodOverrideGetter
MethodFromHeader gets an override method from a request header. @group Middleware - Method Override Example: router := echoweb.New().Router()
router.Use(webmiddleware.MethodOverrideWithConfig(webmiddleware.MethodOverrideConfig{
Getter: webmiddleware.MethodFromHeader("X-HTTP-Method-Override"),
}))
func MethodFromQuery ¶
func MethodFromQuery(param string) MethodOverrideGetter
MethodFromQuery gets an override method from a query parameter. @group Middleware - Method Override Example: router := echoweb.New().Router()
router.Use(webmiddleware.MethodOverrideWithConfig(webmiddleware.MethodOverrideConfig{
Getter: webmiddleware.MethodFromQuery("_method"),
}))
type ProxyBalancer ¶
type ProxyBalancer interface {
AddTarget(*ProxyTarget) bool
RemoveTarget(string) bool
Next(web.Context) *ProxyTarget
}
ProxyBalancer selects upstream targets.
func NewRandomBalancer ¶
func NewRandomBalancer(targets []*ProxyTarget) ProxyBalancer
NewRandomBalancer creates a random proxy balancer. @group Middleware - Proxying Example: target, _ := url.Parse("http://localhost:8080") balancer := webmiddleware.NewRandomBalancer([]*webmiddleware.ProxyTarget{{URL: target}}) fmt.Println(balancer.Next(nil).URL.Host)
// localhost:8080
func NewRoundRobinBalancer ¶
func NewRoundRobinBalancer(targets []*ProxyTarget) ProxyBalancer
NewRoundRobinBalancer creates a round-robin proxy balancer. @group Middleware - Proxying Example: target, _ := url.Parse("http://localhost:8080") balancer := webmiddleware.NewRoundRobinBalancer([]*webmiddleware.ProxyTarget{{URL: target}}) fmt.Println(balancer.Next(nil).URL.Host)
// localhost:8080
type ProxyConfig ¶
type ProxyConfig struct {
Skipper Skipper
Balancer ProxyBalancer
ErrorHandler func(web.Context, error) error
Rewrite map[string]string
RegexRewrite map[*regexp.Regexp]string
ContextKey string
Transport http.RoundTripper
ModifyResponse func(*http.Response) error
}
ProxyConfig configures reverse proxy behavior.
type ProxyTarget ¶
ProxyTarget is an upstream target.
type RateLimiterConfig ¶
type RateLimiterConfig struct {
Skipper Skipper
IdentifierExtractor Extractor
Store RateLimiterStore
ErrorHandler func(web.Context, error) error
DenyHandler func(web.Context, string, error) error
}
RateLimiterConfig configures rate limiting.
type RateLimiterMemoryStore ¶
type RateLimiterMemoryStore struct {
// contains filtered or unexported fields
}
RateLimiterMemoryStore is an in-memory store for rate limiting.
func NewRateLimiterMemoryStore ¶
func NewRateLimiterMemoryStore(limit rate.Limit) *RateLimiterMemoryStore
NewRateLimiterMemoryStore creates an in-memory rate limiter store. @group Middleware - Rate Limiting Example: store := webmiddleware.NewRateLimiterMemoryStore(rate.Every(time.Second)) allowed1, _ := store.Allow("192.0.2.1") allowed2, _ := store.Allow("192.0.2.1") fmt.Println(allowed1, allowed2)
// true false
func NewRateLimiterMemoryStoreWithConfig ¶
func NewRateLimiterMemoryStoreWithConfig(config RateLimiterMemoryStoreConfig) *RateLimiterMemoryStore
NewRateLimiterMemoryStoreWithConfig creates an in-memory rate limiter store with config. @group Middleware - Rate Limiting Example: store := webmiddleware.NewRateLimiterMemoryStoreWithConfig(webmiddleware.RateLimiterMemoryStoreConfig{Rate: rate.Every(time.Second)}) allowed, _ := store.Allow("192.0.2.1") fmt.Println(allowed)
// true
func (*RateLimiterMemoryStore) Allow ¶
func (store *RateLimiterMemoryStore) Allow(identifier string) (bool, error)
Allow checks whether the given identifier is allowed through. @group Middleware - Rate Limiting Example: store := webmiddleware.NewRateLimiterMemoryStore(rate.Every(time.Second)) allowed, err := store.Allow("127.0.0.1") fmt.Println(err == nil, allowed)
// true true
type RateLimiterMemoryStoreConfig ¶
RateLimiterMemoryStoreConfig configures the in-memory rate limiter store.
type RateLimiterStore ¶
RateLimiterStore is the store interface for the rate limiter.
type RecoverConfig ¶
type RecoverConfig struct {
StackSize int
DisableStack bool
DisableErrorHandler bool
HandleError func(web.Context, error, []byte) error
}
RecoverConfig configures recover middleware.
type RedirectConfig ¶
type RedirectConfig struct {
Code int
}
RedirectConfig configures redirect middleware.
type RequestIDConfig ¶
type RequestIDConfig struct {
Generator func() string
TargetHeader string
ContextKey string
RequestIDHandler func(web.Context, string)
}
RequestIDConfig configures request id middleware.
type RequestLoggerConfig ¶
type RequestLoggerConfig struct {
LogValuesFunc func(web.Context, RequestLoggerValues) error
}
RequestLoggerConfig configures request logger middleware.
type RequestLoggerValues ¶
type RequestLoggerValues struct {
Status int
URI string
Method string
Latency time.Duration
Error error
}
RequestLoggerValues are the values captured by request logger middleware.
type RewriteConfig ¶
RewriteConfig configures URL path rewriting.
type SecureConfig ¶
type SecureConfig struct {
Skipper Skipper
XSSProtection string
ContentTypeNosniff string
XFrameOptions string
HSTSMaxAge int
HSTSExcludeSubdomains bool
ContentSecurityPolicy string
CSPReportOnly bool
HSTSPreloadEnabled bool
ReferrerPolicy string
}
SecureConfig configures secure response headers.
type StaticConfig ¶
type StaticConfig struct {
Skipper Skipper
Root string
Index string
HTML5 bool
Browse bool
IgnoreBase bool
Filesystem http.FileSystem
}
StaticConfig configures static file serving.
type TimeoutConfig ¶
type TimeoutConfig struct {
Skipper Skipper
ErrorMessage string
OnTimeoutRouteErrorHandler func(error, web.Context)
Timeout time.Duration
}
TimeoutConfig configures response timeouts.
type TrailingSlashConfig ¶
type TrailingSlashConfig struct {
RedirectCode int
}
TrailingSlashConfig configures slash middleware.
type ValuesExtractor ¶
ValuesExtractor extracts one or more values from a request.
func CreateExtractors ¶
func CreateExtractors(lookups string) ([]ValuesExtractor, error)
CreateExtractors creates extractors from a lookup definition. @group Middleware - Auth Example: extractors, err := webmiddleware.CreateExtractors("header:X-API-Key,query:token") fmt.Println(err == nil, len(extractors))
// true 2