1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00
echo/middleware/request_id.go

65 lines
1.4 KiB
Go
Raw Normal View History

2017-02-10 09:21:32 +02:00
package middleware
import (
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/random"
2017-02-10 09:21:32 +02:00
)
type (
// RequestIDConfig defines the config for RequestID middleware.
RequestIDConfig struct {
// Skipper defines a function to skip middleware.
2017-02-10 10:09:11 +02:00
Skipper Skipper
// Generator defines a function to generate an ID.
// Optional. Default value random.String(32).
Generator func() string
2017-02-10 09:21:32 +02:00
}
)
var (
// DefaultRequestIDConfig is the default RequestID middleware config.
DefaultRequestIDConfig = RequestIDConfig{
Skipper: DefaultSkipper,
Generator: generator,
2017-02-10 09:21:32 +02:00
}
)
// RequestID returns a X-Request-ID middleware.
func RequestID() echo.MiddlewareFunc {
return RequestIDWithConfig(DefaultRequestIDConfig)
}
// RequestIDWithConfig returns a X-Request-ID middleware with config.
func RequestIDWithConfig(config RequestIDConfig) echo.MiddlewareFunc {
// Defaults
2017-02-10 09:21:32 +02:00
if config.Skipper == nil {
config.Skipper = DefaultRequestIDConfig.Skipper
}
if config.Generator == nil {
config.Generator = generator
}
2017-02-10 09:21:32 +02:00
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
req := c.Request()
res := c.Response()
rid := req.Header.Get(echo.HeaderXRequestID)
2017-02-10 09:21:32 +02:00
if rid == "" {
rid = config.Generator()
2017-02-10 09:21:32 +02:00
}
res.Header().Set(echo.HeaderXRequestID, rid)
2017-02-10 09:21:32 +02:00
return next(c)
}
}
}
func generator() string {
return random.String(32)
}