From 489386b49210c4937b79228b5099b302b981b411 Mon Sep 17 00:00:00 2001 From: Elias Kohout Date: Sat, 11 Jan 2025 01:35:25 +0100 Subject: [PATCH] add middleware for request logging --- golang/cmd/frontend/main.go | 4 ++-- golang/cmd/frontend/routes.go | 26 ++++++++++++++++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/golang/cmd/frontend/main.go b/golang/cmd/frontend/main.go index 930649b..ec6e36a 100644 --- a/golang/cmd/frontend/main.go +++ b/golang/cmd/frontend/main.go @@ -25,10 +25,10 @@ func main() { // start web server server := http.Server{ - Addr: ":80", + Addr: ":8080", Handler: app.routes(), } - log.Println("server started, listening on :80") + log.Println("server started, listening on :8080") server.ListenAndServe() } diff --git a/golang/cmd/frontend/routes.go b/golang/cmd/frontend/routes.go index cadaf49..59ec3a7 100644 --- a/golang/cmd/frontend/routes.go +++ b/golang/cmd/frontend/routes.go @@ -1,19 +1,33 @@ package main import ( + "log" "net/http" + "time" ) +// LoggingMiddleware logs details about each incoming HTTP request. +func LoggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + // Call the next handler + next.ServeHTTP(w, r) + + log.Printf("[request] %s %s from %s (%v)", r.URL.Path, r.Method, r.RemoteAddr, time.Since(start)) + }) +} + func (app *App) routes() http.Handler { - mux := http.NewServeMux() + mux := http.NewServeMux() - // dynamic routes - mux.HandleFunc("GET /", app.Index) - mux.HandleFunc("POST /up/search", app.UpSearch) + // dynamic routes + mux.Handle("GET /", LoggingMiddleware(http.HandlerFunc(app.Index))) + mux.Handle("POST /up/search", LoggingMiddleware(http.HandlerFunc(app.UpSearch))) - // serve files from the "static" directory + // serve files from the "static" directory fs := http.FileServer(http.Dir("assets/static")) mux.Handle("GET /static/", http.StripPrefix("/", fs)) - return mux + return mux }