hlog: adds ProtoHandler (#396)
This commit is contained in:
parent
dbdec88d16
commit
14d6629e41
14
hlog/hlog.go
14
hlog/hlog.go
|
@ -121,6 +121,20 @@ func RefererHandler(fieldKey string) func(next http.Handler) http.Handler {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProtoHandler adds the requests protocol version as a field to the context logger
|
||||||
|
// using fieldKey as field Key.
|
||||||
|
func ProtoHandler(fieldKey string) func(next http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
log := zerolog.Ctx(r.Context())
|
||||||
|
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
|
||||||
|
return c.Str(fieldKey, r.Proto)
|
||||||
|
})
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type idKey struct{}
|
type idKey struct{}
|
||||||
|
|
||||||
// IDFromRequest returns the unique id associated to the request if any.
|
// IDFromRequest returns the unique id associated to the request if any.
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
//go:build go1.7
|
||||||
// +build go1.7
|
// +build go1.7
|
||||||
|
|
||||||
package hlog
|
package hlog
|
||||||
|
@ -200,6 +201,22 @@ func TestCustomHeaderHandler(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestProtoHandler(t *testing.T) {
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
r := &http.Request{
|
||||||
|
Proto: "test",
|
||||||
|
}
|
||||||
|
h := ProtoHandler("proto")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
l := FromRequest(r)
|
||||||
|
l.Log().Msg("")
|
||||||
|
}))
|
||||||
|
h = NewHandler(zerolog.New(out))(h)
|
||||||
|
h.ServeHTTP(nil, r)
|
||||||
|
if want, got := `{"proto":"test"}`+"\n", decodeIfBinary(out); want != got {
|
||||||
|
t.Errorf("Invalid log output, got: %s, want: %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCombinedHandlers(t *testing.T) {
|
func TestCombinedHandlers(t *testing.T) {
|
||||||
out := &bytes.Buffer{}
|
out := &bytes.Buffer{}
|
||||||
r := &http.Request{
|
r := &http.Request{
|
||||||
|
|
Loading…
Reference in New Issue