Skip to content

Commit b4f1838

Browse files
committed
Use httptest.Server to fully demonstrate hlog.
It is able to run all the handlers; the former implementation didn't.
1 parent 6abadab commit b4f1838

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

hlog/hlog_example_test.go

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,24 +50,31 @@ func Example_handler() {
5050

5151
// Install some provided extra handlers to set some request's context fields.
5252
// Thanks to those handlers, all our logs will come with some pre-populated fields.
53-
c = c.Append(hlog.RemoteAddrHandler("ip"))
53+
c = c.Append(hlog.HTTPVersionHandler("http_version"))
5454
c = c.Append(hlog.UserAgentHandler("user_agent"))
55-
c = c.Append(hlog.RefererHandler("referer"))
55+
c = c.Append(hlog.URLHandler("url"))
5656
//c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id"))
5757

5858
// Here is your final handler
5959
h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
60+
status := http.StatusOK // Your business logic here
61+
6062
// Get the logger from the request's context. You can safely assume it
6163
// will be always there: if the handler is removed, hlog.FromRequest
6264
// will return a no-op logger.
6365
hlog.FromRequest(r).Info().
6466
Str("user", "current user").
65-
Str("status", "ok").
67+
Int("status", status).
6668
Msg("Something happened")
6769
}))
68-
http.Handle("/", h)
6970

70-
h.ServeHTTP(httptest.NewRecorder(), &http.Request{})
71+
ts := httptest.NewServer(h)
72+
defer ts.Close()
73+
74+
_, err := http.Get(ts.URL)
75+
if err != nil {
76+
panic("http.Get failed")
77+
}
7178

72-
// Output: {"level":"info","role":"my-service","host":"local-hostname","user":"current user","status":"ok","time":"2001-02-03T04:05:06Z","message":"Something happened"}
79+
// Output: {"level":"info","role":"my-service","host":"local-hostname","http_version":"1.1","user_agent":"Go-http-client/1.1","url":"/","user":"current user","status":200,"time":"2001-02-03T04:05:06Z","message":"Something happened"}
7380
}

0 commit comments

Comments
 (0)