-
Notifications
You must be signed in to change notification settings - Fork 4
/
request_id.go
80 lines (63 loc) · 2.07 KB
/
request_id.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Copyright (c) Fabio da Silva Ribeiro <[email protected]>
* SPDX-License-Identifier: MIT
*/
package middleware
import (
"context"
"github.com/gofrs/uuid/v5"
"github.com/labstack/echo/v4"
emw "github.com/labstack/echo/v4/middleware"
)
type ctxkey struct{ name string }
// reqIDKey key used to store the request-id in context.
var reqIDKey = &ctxkey{"request-id"}
// RequestIDConfig alias for emw.RequestIDConfig
type RequestIDConfig = emw.RequestIDConfig
// DefaultRequestIDConfig is the default RequestID middleware config, based on
// the echo.RequestIDConfig but with uuid generator instead.
var DefaultRequestIDConfig = RequestIDConfig{
Skipper: emw.DefaultSkipper,
Generator: uuidGen,
RequestIDHandler: requestIDHandler,
TargetHeader: echo.HeaderXRequestID,
}
// RequestID returns a middleware that reads or generates a new request id and
// returns to response, also stores in context.
func RequestID() echo.MiddlewareFunc {
return RequestIDWithConfig(DefaultRequestIDConfig)
}
// RequestIDWithConfig uses the echo.RequestIDWithConfig under the hood with
// custom generator and sets the request id in context.
func RequestIDWithConfig(cfg RequestIDConfig) echo.MiddlewareFunc {
// Defaults
if cfg.Skipper == nil {
cfg.Skipper = emw.DefaultRequestIDConfig.Skipper
}
if cfg.Generator == nil {
cfg.Generator = uuidGen
}
if cfg.RequestIDHandler == nil {
cfg.RequestIDHandler = requestIDHandler
}
if cfg.TargetHeader == "" {
cfg.TargetHeader = echo.HeaderXRequestID
}
return emw.RequestIDWithConfig(cfg)
}
// uuidGen generates a random uuid.V4.
func uuidGen() string {
return uuid.Must(uuid.NewV4()).String()
}
// requestIDHandler sets the received request-id into request context.
func requestIDHandler(ec echo.Context, rid string) {
req := ec.Request()
ctx := context.WithValue(req.Context(), reqIDKey, rid)
ec.SetRequest(req.WithContext(ctx))
}
// RequestIDValue returns the value stored in the context, otherwise returns an
// empty string
func RequestIDValue(ctx context.Context) string {
v, _ := ctx.Value(reqIDKey).(string)
return v
}