all repos

x @ da217b4426264b3ac4861ce9411bcff61cb3426b

go extra()

x/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
51
52
53
54
55
56
57
58
59
60
61
62
63
package reqid

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"net/http"
)

type requestIDKey string

const (
	RequestID requestIDKey = "request-id"

	Header = "X-Request-ID"
)

// Middleware http middleware that sets random generated request id to each
// request it get fed.
func Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rid := r.Header.Get(Header)
		if rid == "" {
			rid = generateRequestID()
			r.Header.Set(Header, rid)
		}

		ctx := SetContext(r.Context(), rid)
		r = r.WithContext(ctx)

		w.Header().Add(Header, rid)
		next.ServeHTTP(w, r)
	})
}

// Get returns the request ID of http request (looks up from headers)
func Get(r *http.Request) string {
	return r.Header.Get(Header)
}

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

// SetContext gets a parent context and returns a child context with the set
// provided request ID
func SetContext(ctx context.Context, reqID string) context.Context {
	return context.WithValue(ctx, RequestID, reqID)
}

func generateRequestID() string {
	b := make([]byte, 13)
	_, err := rand.Read(b)
	if err != nil {
		return "unknown"
	}
	return hex.EncodeToString(b)
}