Skip to content

Commit 3335362

Browse files
authored
Add simple logging to example-shttp-fileserver (#157)
Not entirely sure this still fits the scope of an "example". Log requests requests in a simple format: <time> <remote address> "<request>" <status code> <size of reply> for example 2020/07/29 07:49:13 19-ffaa:1:106,127.0.0.1:3173 "GET /foo HTTP/3/SCION" 200 4
1 parent e3c9c83 commit 3335362

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

_examples/shttp/fileserver/main.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,38 @@ func main() {
3030
flag.Parse()
3131

3232
handler := http.FileServer(http.Dir(""))
33-
log.Fatal(shttp.ListenAndServe(fmt.Sprintf(":%d", *port), handler, nil))
33+
log.Fatal(shttp.ListenAndServe(fmt.Sprintf(":%d", *port), withLogger(handler), nil))
34+
}
35+
36+
// withLogger returns a handler that logs requests (after completion) in a simple format:
37+
// <time> <remote address> "<request>" <status code> <size of reply>
38+
func withLogger(h http.Handler) http.Handler {
39+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
40+
wrec := &recordingResponseWriter{ResponseWriter: w}
41+
h.ServeHTTP(wrec, r)
42+
43+
log.Printf("%s \"%s %s %s/SCION\" %d %d\n",
44+
r.RemoteAddr,
45+
r.Method, r.URL, r.Proto,
46+
wrec.status, wrec.bytes)
47+
})
48+
}
49+
50+
type recordingResponseWriter struct {
51+
http.ResponseWriter
52+
status int
53+
bytes int
54+
}
55+
56+
func (r *recordingResponseWriter) WriteHeader(statusCode int) {
57+
r.status = statusCode
58+
r.ResponseWriter.WriteHeader(statusCode)
59+
}
60+
61+
func (r *recordingResponseWriter) Write(b []byte) (int, error) {
62+
if r.status == 0 {
63+
r.status = http.StatusOK
64+
}
65+
r.bytes += len(b)
66+
return r.ResponseWriter.Write(b)
3467
}

0 commit comments

Comments
 (0)