/
util.go
65 lines (48 loc) · 1.31 KB
/
util.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
// Package util provides UUIDs for CarbonAPI and CarbonZipper HTTP requests.
package util
import (
"context"
"net/http"
"github.com/satori/go.uuid"
)
type key int
const (
ctxHeaderUUID = "X-CTX-CarbonAPI-UUID"
uuidKey key = 0
)
// GetUUID gets the Carbon UUID of a request.
func GetUUID(ctx context.Context) string {
if id := ctx.Value(uuidKey); id != nil {
return id.(string)
}
return ""
}
// MarshalCtx ensures that outgoing HTTP requests have a Carbon UUID.
func MarshalCtx(ctx context.Context, request *http.Request) *http.Request {
ctx = WithUUID(ctx)
request.Header.Add(ctxHeaderUUID, GetUUID(ctx))
return request
}
// WithUUID ensures that a context has a Carbon UUID.
func WithUUID(ctx context.Context) context.Context {
if id := GetUUID(ctx); id != "" {
return ctx
}
id := uuid.NewV4().String()
return context.WithValue(ctx, uuidKey, id)
}
type uuidHandler struct {
handler http.Handler
}
// UUIDHandler is middleware that adds a Carbon UUID to all HTTP requests.
func UUIDHandler(h http.Handler) http.Handler {
return uuidHandler{handler: h}
}
func (h uuidHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(ctxHeaderUUID)
if id == "" {
id = uuid.NewV4().String()
}
ctx := context.WithValue(r.Context(), uuidKey, id)
h.handler.ServeHTTP(w, r.WithContext(ctx))
}