forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/labstack/echo/v4/middleware/request_id.go

76 lines
1.9 KiB
Go
Raw Normal View History

2024-05-14 13:07:09 +00:00
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
2024-02-18 10:42:21 +00:00
package middleware
import (
"github.com/labstack/echo/v4"
)
2024-05-14 13:07:09 +00:00
// RequestIDConfig defines the config for RequestID middleware.
type RequestIDConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
2024-02-18 10:42:21 +00:00
2024-05-14 13:07:09 +00:00
// Generator defines a function to generate an ID.
// Optional. Defaults to generator for random string of length 32.
Generator func() string
2024-02-18 10:42:21 +00:00
2024-05-14 13:07:09 +00:00
// RequestIDHandler defines a function which is executed for a request id.
RequestIDHandler func(echo.Context, string)
2024-02-18 10:42:21 +00:00
2024-05-14 13:07:09 +00:00
// TargetHeader defines what header to look for to populate the id
TargetHeader string
}
2024-02-18 10:42:21 +00:00
2024-05-14 13:07:09 +00:00
// DefaultRequestIDConfig is the default RequestID middleware config.
var DefaultRequestIDConfig = RequestIDConfig{
Skipper: DefaultSkipper,
Generator: generator,
TargetHeader: echo.HeaderXRequestID,
}
2024-02-18 10:42:21 +00: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
if config.Skipper == nil {
config.Skipper = DefaultRequestIDConfig.Skipper
}
if config.Generator == nil {
config.Generator = generator
}
if config.TargetHeader == "" {
config.TargetHeader = echo.HeaderXRequestID
}
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(config.TargetHeader)
if rid == "" {
rid = config.Generator()
}
res.Header().Set(config.TargetHeader, rid)
if config.RequestIDHandler != nil {
config.RequestIDHandler(c, rid)
}
return next(c)
}
}
}
func generator() string {
return randomString(32)
}