all repos

onasty @ bcf505635318b83f2b5338c2274ea658a2a23758

a one-time notes service

onasty/internal/transport/http/reqid/reqid.go(view raw)

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// reqid provides gin-gonic/gin middleware to generate a requestid for each request
package reqid

import (
	"context"

	"github.com/gin-gonic/gin"
	"github.com/gofrs/uuid/v5"
)

type requestIDKey string

const (
	RequestID requestIDKey = "request_id"

	headerRequestID = "X-Request-ID"
)

// Middleware initializes the request ID
func Middleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		rid := c.GetHeader(headerRequestID)
		if rid == "" {
			rid = uuid.Must(uuid.NewV4()).String()
			c.Request.Header.Add(headerRequestID, rid)
		}

		// set reqeust ID request context
		ctx := context.WithValue(c.Request.Context(), RequestID, rid)
		c.Request = c.Request.WithContext(ctx)

		// ensures that the request ID is in the response
		c.Header(headerRequestID, rid)
		c.Next()
	}
}

// Get returns the request ID
func Get(c *gin.Context) string {
	return c.GetHeader(headerRequestID)
}

// GetContext returns the request ID from context
func GetContext(ctx context.Context) string {
	rid, ok := ctx.Value(RequestID).(string)
	if !ok {
		return ""
	}
	return rid
}