1 Star 0 Fork 0

妥協/fabric

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
request_id.go 992 Bytes
一键复制 编辑 原始数据 按行查看 历史
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package middleware
import (
"context"
"net/http"
)
var requestIDKey = requestIDKeyType{}
type requestIDKeyType struct{}
func RequestID(ctx context.Context) string {
if reqID, ok := ctx.Value(requestIDKey).(string); ok {
return reqID
}
return "unknown"
}
type GenerateIDFunc func() string
type requestID struct {
generateID GenerateIDFunc
next http.Handler
}
func WithRequestID(generator GenerateIDFunc) Middleware {
return func(next http.Handler) http.Handler {
return &requestID{next: next, generateID: generator}
}
}
func (r *requestID) ServeHTTP(w http.ResponseWriter, req *http.Request) {
reqID := req.Header.Get("X-Request-Id")
if reqID == "" {
reqID = r.generateID()
req.Header.Set("X-Request-Id", reqID)
}
ctx := context.WithValue(req.Context(), requestIDKey, reqID)
req = req.WithContext(ctx)
w.Header().Add("X-Request-Id", reqID)
r.next.ServeHTTP(w, req)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/liurenhao/fabric.git
git@gitee.com:liurenhao/fabric.git
liurenhao
fabric
fabric
v2.0.0

搜索帮助

0d507c66 1850385 C8b1a773 1850385