httprouter
                                
                                
                                
                                    httprouter copied to clipboard
                            
                            
                            
                        how to log response status code
For some reason the request's response object is nil, even when using defer.
How do I log the status code the endpoint resulted with?
func LogHandler(h httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		lc := ToContext(r.Context(), SetupLogrus())
		requestID := r.Header.Get(REQUEST_ID)
		if requestID == "" {
			requestID = string(composeRequestID())
			r.Header.Set(REQUEST_ID, string(requestID))
		}
		f := setupRequestFields(r.Context(), w, r)
		delete(f, "status")
		AddFields(lc, f)
		req := r.WithContext(lc)
		h(w, req, ps)
		defer func() {
			l := Extract(lc)
			l.WithField("status", req.Response.StatusCode).Infof("%s %s", string(r.Method), r.URL)
		}()
	}
}
                                    
                                    
                                    
                                
func logger() midfunc {
    return func(next httprouter.Handle) httprouter.Handle {
        return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
            start := time.Now()
            // Initialize the status to 200 in case WriteHeader is not called
            sw := statusRecorder{w, 200}
            next(&sw, r, ps)
            log.Printf("[%s: %s :%d] [time: %v]\n", r.Method, r.URL.String(), sw.status, time.Since(start))
            return
        }
    }
}