forked from smallstep/certificates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
66 lines (55 loc) · 1.87 KB
/
context.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
package logging
import (
"context"
"net/http"
"github.com/rs/xid"
)
type key int
const (
// RequestIDKey is the context key that should store the request identifier.
RequestIDKey key = iota
// UserIDKey is the context key that should store the user identifier.
UserIDKey
)
// NewRequestID creates a new request id using github.com/rs/xid.
func NewRequestID() string {
return xid.New().String()
}
// RequestID returns a new middleware that gets the given header and sets it
// in the context so it can be written in the logger. If the header does not
// exists or it's the empty string, it uses github.com/rs/xid to create a new
// one.
func RequestID(headerName string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
requestID := req.Header.Get(headerName)
if requestID == "" {
requestID = NewRequestID()
req.Header.Set(headerName, requestID)
}
ctx := WithRequestID(req.Context(), requestID)
next.ServeHTTP(w, req.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
}
// WithRequestID returns a new context with the given requestID added to the
// context.
func WithRequestID(ctx context.Context, requestID string) context.Context {
return context.WithValue(ctx, RequestIDKey, requestID)
}
// GetRequestID returns the request id from the context if it exists.
func GetRequestID(ctx context.Context) (string, bool) {
v, ok := ctx.Value(RequestIDKey).(string)
return v, ok
}
// WithUserID decodes the token, extracts the user from the payload and stores
// it in the context.
func WithUserID(ctx context.Context, userID string) context.Context {
return context.WithValue(ctx, UserIDKey, userID)
}
// GetUserID returns the request id from the context if it exists.
func GetUserID(ctx context.Context) (string, bool) {
v, ok := ctx.Value(UserIDKey).(string)
return v, ok
}