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)
}
>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.