diff options
author | EuAndreh <eu@euandre.org> | 2024-11-10 09:14:06 -0300 |
---|---|---|
committer | EuAndreh <eu@euandre.org> | 2024-11-10 09:14:06 -0300 |
commit | 97fc9ef5f083456ada4bfe7ce546a6f3609d25e1 (patch) | |
tree | e7031406285d10fb92a4e2680ba36cbc6914a77a | |
parent | src/glaze.go: Return 404 instead of 500 on missing file (diff) | |
download | glaze-97fc9ef5f083456ada4bfe7ce546a6f3609d25e1.tar.gz glaze-97fc9ef5f083456ada4bfe7ce546a6f3609d25e1.tar.xz |
src/glaze.go: Separate logging from handling
-rw-r--r-- | src/glaze.go | 48 |
1 files changed, 43 insertions, 5 deletions
diff --git a/src/glaze.go b/src/glaze.go index 959cf30..c4fc9df 100644 --- a/src/glaze.go +++ b/src/glaze.go @@ -12,8 +12,10 @@ import ( "net/http" "net/url" "os" + "slices" "strings" "syscall" + "time" "guuid" g "gobang" @@ -209,12 +211,42 @@ func handlerForDynPath(path string) (pathInfo, func(pathInfo, http.ResponseWrite return info, fn, nil } -func handlerFor(path string) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { +func logged(pattern string, path string, handler http.HandlerFunc) http.HandlerFunc { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() id := guuid.New().String() - g.Info("in-request", "in-request", "path", path, "id", id) - defer g.Info("in-response", "in-response", "path", path, "id", id) + args := []any{ + "id", id, + "pattern", []string{ pattern, path }, + "url-path", r.URL.Path, + "req-pattern", r.Pattern, + "method", r.Method, + "host", r.Host, + "uri", r.RequestURI, + } + g.Info( + "in-request", "in-request", + args..., + ) + handler(w, r) + durationNano := time.Since(start) + durationMilli := float64(durationNano) / float64(time.Millisecond) + g.Info( + "in-response", "in-response", + slices.Concat( + []any{ + "duration-ns", durationNano, + "duration-ms", durationMilli, + }, + args, + )..., + ) + }) +} + +func handlerFor(path string) http.HandlerFunc { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { info, fn, err := handlerForDynPath(path) if err != nil { httpError(w, http.StatusInternalServerError, err) @@ -242,7 +274,13 @@ func (_ *patternPath) Set(value string) error { pattern := adjustPattern(arr[0]) path := arr[1] - http.Handle(pattern, http.StripPrefix(pattern, handlerFor(path))) + http.Handle( + pattern, + http.StripPrefix( + pattern, + logged(pattern, path, handlerFor(path)), + ), + ) return nil } |