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) {
var rid string
if rid = ctx.GetString(requestID); rid != "" {
// request id exists already
ctx.Next()
}
if rid = ctx.GetHeader(requestID); rid != "" {
ctx.Set(requestID, rid)
ctx.Request.Header.Add(requestID, rid)
ctx.Next()
}
rid = uuid.NewString()
ctx.Set(requestID, rid)
ctx.Writer.Header().Add(requestID, rid)
ctx.Request.Header.Add(requestID, rid)
ctx.Header(requestID, rid)
ctx.Next()
}
}

View File

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