forked from atarantini/ginrequestid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequestid.go
More file actions
33 lines (28 loc) · 777 Bytes
/
requestid.go
File metadata and controls
33 lines (28 loc) · 777 Bytes
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
33
//
// ginrequestid
//
// Set an UUID4 string as Request ID into response headers ("X-Request-Id") and
// expose that value as "RequestId" in order to use it inside the application for logging
// or propagation to other systems.
//
package ginrequestid
import (
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
)
func RequestId() gin.HandlerFunc {
return func(c *gin.Context) {
// Check for incoming header, use it if exists
requestID := c.Request.Header.Get("X-Request-Id")
// Create request id with UUID4
if requestID == "" {
uuid4, _ := uuid.NewV4()
requestID = uuid4.String()
}
// Expose it for use in the application
c.Set("RequestId", requestID)
// Set X-Request-Id header
c.Writer.Header().Set("X-Request-Id", requestID)
c.Next()
}
}