Add request logging
This commit is contained in:
parent
19843f416f
commit
91415af5c3
1 changed files with 14 additions and 0 deletions
14
main.go
14
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")
|
||||
})
|
||||
|
||||
|
|
Loading…
Reference in a new issue