feat: create session. (also print the x-rid into the log)

This commit is contained in:
Muyao CHEN
2024-10-11 23:24:29 +02:00
parent be7f57d5a1
commit a3c2ade9fb
10 changed files with 105 additions and 36 deletions

View File

@ -27,20 +27,20 @@ import (
"github.com/google/uuid"
)
const requestID = "X-Request-Id"
const XRequestID = "X-Request-Id"
func RequestID() gin.HandlerFunc {
return func(ctx *gin.Context) {
var rid string
if rid = ctx.GetHeader(requestID); rid != "" {
ctx.Request.Header.Add(requestID, rid)
if rid = ctx.GetHeader(XRequestID); rid != "" {
ctx.Request.Header.Add(XRequestID, rid)
ctx.Next()
}
rid = uuid.NewString()
ctx.Request.Header.Add(requestID, rid)
ctx.Header(requestID, rid)
ctx.Request.Header.Add(XRequestID, rid)
ctx.Header(XRequestID, rid)
ctx.Next()
}
}

View File

@ -58,21 +58,21 @@ func TestRequestID(t *testing.T) {
wanted := "123"
r.GET("/example", func(c *gin.Context) {
got = c.GetHeader(requestID)
got = c.GetHeader(XRequestID)
c.Status(http.StatusOK)
})
r.POST("/example", func(c *gin.Context) {
got = c.GetHeader(requestID)
got = c.GetHeader(XRequestID)
c.String(http.StatusAccepted, "ok")
})
// Test with Request ID
_ = performRequest(r, "GET", "/example?a=100", header{requestID, wanted})
_ = performRequest(r, "GET", "/example?a=100", header{XRequestID, wanted})
assert.Equal(t, "123", got)
res := performRequest(r, "GET", "/example?a=100")
assert.NotEqual(t, "", got)
assert.NoError(t, uuid.Validate(got))
assert.Equal(t, res.Header()[requestID][0], got)
assert.Equal(t, res.Header()[XRequestID][0], got)
}