add middleware for request logging
This commit is contained in:
@@ -25,10 +25,10 @@ func main() {
|
|||||||
|
|
||||||
// start web server
|
// start web server
|
||||||
server := http.Server{
|
server := http.Server{
|
||||||
Addr: ":80",
|
Addr: ":8080",
|
||||||
Handler: app.routes(),
|
Handler: app.routes(),
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("server started, listening on :80")
|
log.Println("server started, listening on :8080")
|
||||||
server.ListenAndServe()
|
server.ListenAndServe()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,33 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log"
|
||||||
"net/http"
|
"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 {
|
func (app *App) routes() http.Handler {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
// dynamic routes
|
// dynamic routes
|
||||||
mux.HandleFunc("GET /", app.Index)
|
mux.Handle("GET /", LoggingMiddleware(http.HandlerFunc(app.Index)))
|
||||||
mux.HandleFunc("POST /up/search", app.UpSearch)
|
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"))
|
fs := http.FileServer(http.Dir("assets/static"))
|
||||||
mux.Handle("GET /static/", http.StripPrefix("/", fs))
|
mux.Handle("GET /static/", http.StripPrefix("/", fs))
|
||||||
|
|
||||||
return mux
|
return mux
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user