-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathhandler_pre17.go
60 lines (50 loc) · 1.77 KB
/
handler_pre17.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
// +build !go1.7
package xstats
import (
"net/http"
"github.com/rs/xhandler"
"golang.org/x/net/context"
)
// Handler injects a per request metrics client in the net/context which can be
// retrived using xstats.FromContext(ctx)
type Handler struct {
s Sender
tags []string
prefix string
}
type key int
const xstatsKey key = 0
// NewContext returns a copy of the parent context and associates it with passed stats.
func NewContext(ctx context.Context, xs XStater) context.Context {
return context.WithValue(ctx, xstatsKey, xs)
}
// FromContext retreives the request's xstats client from a given context if any.
// If no xstats is embeded in the context, a nop instance is returned so you can
// use it safely without having to test for it's presence.
func FromContext(ctx context.Context) XStater {
rc, ok := ctx.Value(xstatsKey).(XStater)
if ok {
return rc
}
return nop
}
// NewHandler creates a new handler with the provided metric client.
// If some tags are provided, the will be added to all logged metrics.
func NewHandler(s Sender, tags []string) func(xhandler.HandlerC) xhandler.HandlerC {
return NewHandlerPrefix(s, tags, "")
}
// NewHandlerPrefix creates a new handler with the provided metric client.
// If some tags are provided, the will be added to all logged metrics.
// If the prefix argument is provided, all produced metrics will have this
// prefix prepended.
func NewHandlerPrefix(s Sender, tags []string, prefix string) func(xhandler.HandlerC) xhandler.HandlerC {
return func(next xhandler.HandlerC) xhandler.HandlerC {
return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
xs := NewPrefix(s, prefix).(*xstats)
xs.AddTags(tags...)
ctx = NewContext(ctx, xs)
next.ServeHTTPC(ctx, w, r)
xs.Close()
})
}
}