fix: set request id into headers instead of context directly

This commit is contained in:
Muyao CHEN 2024-10-04 23:37:48 +02:00
parent b9d4a58d71
commit ab26e9d585
2 changed files with 5 additions and 10 deletions

View File

@ -33,19 +33,14 @@ func RequestID() gin.HandlerFunc {
return func(ctx *gin.Context) { return func(ctx *gin.Context) {
var rid string var rid string
if rid = ctx.GetString(requestID); rid != "" {
// request id exists already
ctx.Next()
}
if rid = ctx.GetHeader(requestID); rid != "" { if rid = ctx.GetHeader(requestID); rid != "" {
ctx.Set(requestID, rid) ctx.Request.Header.Add(requestID, rid)
ctx.Next() ctx.Next()
} }
rid = uuid.NewString() rid = uuid.NewString()
ctx.Set(requestID, rid) ctx.Request.Header.Add(requestID, rid)
ctx.Writer.Header().Add(requestID, rid) ctx.Header(requestID, rid)
ctx.Next() ctx.Next()
} }
} }

View File

@ -58,12 +58,12 @@ func TestRequestID(t *testing.T) {
wanted := "123" wanted := "123"
r.GET("/example", func(c *gin.Context) { r.GET("/example", func(c *gin.Context) {
got = c.GetString(requestID) got = c.GetHeader(requestID)
c.Status(http.StatusOK) c.Status(http.StatusOK)
}) })
r.POST("/example", func(c *gin.Context) { r.POST("/example", func(c *gin.Context) {
got = c.GetString(requestID) got = c.GetHeader(requestID)
c.String(http.StatusAccepted, "ok") c.String(http.StatusAccepted, "ok")
}) })