-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestid.go
32 lines (25 loc) · 1.04 KB
/
requestid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Copyright 2022 Innkeeper Belm(孔令飞) <nosbelm@qq.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://github.com/marmotedu/miniblog.
package middleware
import (
"github.com/qppHUST/blog/internal/pkg/known"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// RequestID 是一个 Gin 中间件,用来在每一个 HTTP 请求的 context, response 中注入 `X-Request-ID` 键值对.
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
// 检查请求头中是否有 `X-Request-ID`,如果有则复用,没有则新建
requestID := c.Request.Header.Get(known.XRequestIDKey)
if requestID == "" {
requestID = uuid.New().String()
}
// 将 RequestID 保存在 gin.Context 中,方便后边程序使用
c.Set(known.XRequestIDKey, requestID)
// 将 RequestID 保存在 HTTP 返回头中,Header 的键为 `X-Request-ID`
c.Writer.Header().Set(known.XRequestIDKey, requestID)
c.Next()
}
}