Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang custom ServeHTTP status logging

I am building my own web framework, and I have faced with problem, when I try to log the request with response status code, i got err: invalid memory address or nil pointer dereference

My ServeHTTP func:

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {

    handler := r.getHandler(req.Method, req.URL.Path)
    if handler == nil {
        notFoundHandler(w, req)
        return
    }
    done := make(chan struct{})

    reqStruct := newReqStruct(w, req)

    go func() {
        handler(reqStruct)
        done <- struct{}{}
        close(done)
    }()
    <-done
    logger.logRequest(req.URL.Path, req.Method, req.Response.StatusCode)

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This line:

    logger.logRequest(req.URL.Path, req.Method, req.Response.StatusCode)

req.Response will only be populated for HTTP redirects. In this case, it will be nil.

If you want to capture the response code, write a wrapper response writer and implement WriteHeader to capture the response code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading