matterbridge/vendor/github.com/labstack/echo/v4/middleware/request_id.go

71 lines
1.6 KiB
Go
Raw Normal View History

2017-06-05 22:01:05 +00:00
package middleware
import (
"github.com/labstack/echo/v4"
2017-06-05 22:01:05 +00:00
"github.com/labstack/gommon/random"
)
type (
// RequestIDConfig defines the config for RequestID middleware.
RequestIDConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Generator defines a function to generate an ID.
// Optional. Default value random.String(32).
Generator func() string
2021-07-31 16:27:55 +00:00
// RequestIDHandler defines a function which is executed for a request id.
RequestIDHandler func(echo.Context, string)
2017-06-05 22:01:05 +00:00
}
)
var (
// DefaultRequestIDConfig is the default RequestID middleware config.
DefaultRequestIDConfig = RequestIDConfig{
Skipper: DefaultSkipper,
Generator: generator,
}
)
// 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
if config.Skipper == nil {
config.Skipper = DefaultRequestIDConfig.Skipper
}
if config.Generator == nil {
config.Generator = generator
}
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)
if rid == "" {
rid = config.Generator()
}
res.Header().Set(echo.HeaderXRequestID, rid)
2021-07-31 16:27:55 +00:00
if config.RequestIDHandler != nil {
config.RequestIDHandler(c, rid)
}
2017-06-05 22:01:05 +00:00
return next(c)
}
}
}
func generator() string {
return random.String(32)
}