1 Star 2 Fork 0

阿债/fiber-u8l

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
requestid.go 1.73 KB
一键复制 编辑 原始数据 按行查看 历史
阿债 提交于 2020-11-09 18:55 . 更新fiber到2.1.4
package requestid
import (
"gitee.com/azhai/fiber-u8l"
"gitee.com/azhai/fiber-u8l/utils"
)
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Header is the header key where to get/set the unique request ID
//
// Optional. Default: "X-Request-ID"
Header string
// Generator defines a function to generate the unique identifier.
//
// Optional. Default: utils.UUID
Generator func() string
// ContextKey defines the key used when storing the request ID in
// the locals for a specific request.
//
// Optional. Default: requestid
ContextKey string
}
// ConfigDefault is the default config
var ConfigDefault = Config{
Next: nil,
Header: fiber.HeaderXRequestID,
Generator: utils.UUID,
ContextKey: "requestid",
}
// New creates a new middleware handler
func New(config ...Config) fiber.Handler {
// Set default config
cfg := ConfigDefault
// Override config if provided
if len(config) > 0 {
cfg = config[0]
// Set default values
if cfg.Header == "" {
cfg.Header = ConfigDefault.Header
}
if cfg.Generator == nil {
cfg.Generator = ConfigDefault.Generator
}
if cfg.ContextKey == "" {
cfg.ContextKey = ConfigDefault.ContextKey
}
}
// Return new handler
return func(c *fiber.Ctx) error {
// Don't execute middleware if Next returns true
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
// Get id from request, else we generate one
rid := c.Get(cfg.Header, cfg.Generator())
// Set new id to response header
c.Set(cfg.Header, rid)
// Add the request ID to locals
c.Locals(cfg.ContextKey, rid)
// Continue stack
return c.Next()
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/azhai/fiber-u8l.git
git@gitee.com:azhai/fiber-u8l.git
azhai
fiber-u8l
fiber-u8l
v1.21.4

搜索帮助

0d507c66 1850385 C8b1a773 1850385