From 91415af5c33b4b6ae2b782a8c05539a638678b61 Mon Sep 17 00:00:00 2001 From: Ethan Marshall Date: Tue, 23 Jan 2024 00:05:55 +0000 Subject: [PATCH] Add request logging --- main.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/main.go b/main.go index 515e273..d3382c4 100644 --- a/main.go +++ b/main.go @@ -20,18 +20,27 @@ var ( indexTmpl = template.Must(template.ParseFiles("index.gohtml")) ) +func logRequest(response int, r *http.Request) { + log.Printf("[%s] %s %s %d", r.RemoteAddr, r.Method, r.RequestURI, response) +} + func handleRoot(w http.ResponseWriter, r *http.Request) { if r.RequestURI != "/" { + logRequest(404, r) + w.WriteHeader(http.StatusNotFound) w.Write([]byte("404 not found")) return } + logRequest(200, r) indexTmpl.Execute(w, nil) } func handleAPI(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" || r.RequestURI != "/api" { + logRequest(404, r) + w.WriteHeader(http.StatusNotFound) w.Write([]byte("404 not found")) return @@ -44,6 +53,8 @@ func handleAPI(w http.ResponseWriter, r *http.Request) { b, err := json.Marshal(a) if err != nil { + logRequest(500, r) + w.WriteHeader(http.StatusInternalServerError) b, _ = json.Marshal(map[string]any{ "status": "Failed", @@ -51,6 +62,7 @@ func handleAPI(w http.ResponseWriter, r *http.Request) { }) } + logRequest(200, r) w.Write(b) } @@ -67,9 +79,11 @@ func main() { http.HandleFunc("/", handleRoot) http.HandleFunc("/api", handleAPI) http.HandleFunc("/index.css", func(w http.ResponseWriter, r *http.Request) { + logRequest(200, r) http.ServeFile(w, r, "index.css") }) http.HandleFunc("/index.js", func(w http.ResponseWriter, r *http.Request) { + logRequest(200, r) http.ServeFile(w, r, "index.js") })