add middleware for request logging

This commit is contained in:
2025-01-11 01:35:25 +01:00
parent e4e88caaa7
commit 489386b492
2 changed files with 22 additions and 8 deletions

View File

@@ -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()
}

View File

@@ -1,15 +1,29 @@
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()
// dynamic routes
mux.HandleFunc("GET /", app.Index)
mux.HandleFunc("POST /up/search", app.UpSearch)
mux.Handle("GET /", LoggingMiddleware(http.HandlerFunc(app.Index)))
mux.Handle("POST /up/search", LoggingMiddleware(http.HandlerFunc(app.UpSearch)))
// serve files from the "static" directory
fs := http.FileServer(http.Dir("assets/static"))