-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_id.go
More file actions
67 lines (57 loc) · 1.47 KB
/
Copy pathrequest_id.go
File metadata and controls
67 lines (57 loc) · 1.47 KB
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
package httpmw
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"strconv"
"strings"
"time"
)
const DefaultRequestIDHeader = "X-Request-ID"
type requestIDContextKey struct{}
type RequestIDOptions struct {
HeaderName string
Generator func() string
TrustIncoming bool
}
func (o RequestIDOptions) normalized() RequestIDOptions {
if o.HeaderName == "" {
o.HeaderName = DefaultRequestIDHeader
}
if o.Generator == nil {
o.Generator = NewRequestID
}
return o
}
// RequestID injects a request id into the request context and response header.
func RequestID(opts RequestIDOptions) Middleware {
opts = opts.normalized()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := ""
if opts.TrustIncoming {
id = strings.TrimSpace(r.Header.Get(opts.HeaderName))
}
if id == "" {
id = opts.Generator()
}
w.Header().Set(opts.HeaderName, id)
ctx := context.WithValue(r.Context(), requestIDContextKey{}, id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// NewRequestID generates a compact random request id.
func NewRequestID() string {
var buf [16]byte
if _, err := rand.Read(buf[:]); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 36)
}
return hex.EncodeToString(buf[:])
}
// GetRequestID returns the request id stored in the context.
func GetRequestID(ctx context.Context) string {
value, _ := ctx.Value(requestIDContextKey{}).(string)
return value
}