-
Notifications
You must be signed in to change notification settings - Fork 0
/
txmiddleware.go
55 lines (48 loc) · 1.31 KB
/
txmiddleware.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package trex
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
// Injects a transaction context dependency into the gin context
// The transaction context should contain traced dependencies
// such as dbs and https clients
func TxContextMiddleware(factory TxFactory) gin.HandlerFunc {
return func(c *gin.Context) {
// Get and decode the traceparent header into smaller values
trcprnt := c.GetHeader("traceparent")
ver, tid, pid, flg, err := DecodeTraceparent(trcprnt)
// If the header could not be decoded, generate a new header
if err != nil {
ver, flg = "00", "01"
if tid, err = GenerateRadomHexString(16); err != nil {
c.AbortWithError(
http.StatusInternalServerError,
fmt.Errorf("failed to generate trace id %w", err),
)
return
}
pid = tid
}
// Generate a new resource id
rid, err := GenerateRadomHexString(8)
if err != nil {
c.AbortWithError(
http.StatusInternalServerError,
fmt.Errorf("failed to generate resource id %w", err),
)
return
}
// Generate a transaction context usin the factory
txc, err := factory.Generate(ver, tid, pid, rid, flg)
if err != nil {
c.AbortWithError(
http.StatusInternalServerError,
fmt.Errorf("failed to generate transaction context %w", err),
)
return
}
c.Set("tx-context", txc)
c.Next()
}
}