How to log HTTP server errors in golang?

I am trying to catch and log an http error 400 that occurs when url parameters are not encoded properly.

My server implementation looks like this:

router := http.NewServeMux()
router.HandleFunc("/", requestHandler)

s := &http.Server{
    Addr:           ":8080",
    Handler:        router,
    ErrorLog:       myLogger,
}
log.Fatal(s.ListenAndServe())

      

The request never reaches requestHandler

and ErrorLog: myLogger

doesn't matter.

+3


source to share


2 answers


You need to create a custom Wrapper around the requestHandler that records the StatusCode and validates it after the request has been processed.

Notice how we wrap the main router. fromWrapHandler(router)



package main

import (
    "log"
    "net/http"
)

type LogRecord struct {
    http.ResponseWriter
    status int
}

func (r *LogRecord) Write(p []byte) (int, error) {
    return r.ResponseWriter.Write(p)
}

func (r *LogRecord) WriteHeader(status int) {
    r.status = status
    r.ResponseWriter.WriteHeader(status)
}

func WrapHandler(f http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        record := &LogRecord{
            ResponseWriter: w,
        }

        f.ServeHTTP(record, r)

        log.Println("Bad Request ", record.status)

        if record.status == http.StatusBadRequest {
            log.Println("Bad Request ", r)
        }
    }
}

func main() {
    router := http.NewServeMux()

    s := &http.Server{
        Addr:    ":8080",
        Handler: WrapHandler(router),
    }
    log.Fatal(s.ListenAndServe())
}

      

+7


source


Just for anyone else who finds it, you can't catch the 400 error with net / http in Go. See this answer for more details:



How do I customize Golang HTTP 400 responses for parsing errors?

0


source







All Articles