How do I get http status from my own ServeHTTP function

4,194 views
Skip to first unread message

Jackie Li

unread,
Oct 24, 2012, 10:41:41 AM10/24/12
to golan...@googlegroups.com
Hello everyone,

I'm trying to print a log on every http request like this:
date [url] - httpstatus
e.g.: 2012/10/24 15:30:23 [127.0.0.1:56485] / - 200

And I construct my own http.Handler like this:

type WrapHTTPHandler struct {
m *http.Handler
}

func (h *WrapHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.m.ServeHTTP(w, r)
log.Printf("[%s] %s\n", r.RemoteAddr, r.URL)
}

But I couldn't find out how to get the http status code. 

Seems the status code is written directly to the response body, and there is no status code stored in http.Header, is it possible to get the status code here?


Thanks,
Jackie

James McKaskill

unread,
Oct 24, 2012, 11:21:28 AM10/24/12
to Jackie Li, golan...@googlegroups.com
On Wed, Oct 24, 2012 at 9:41 AM, Jackie Li <jackie...@gmail.com> wrote:
> Seems the status code is written directly to the response body, and there is
> no status code stored in http.Header, is it possible to get the status code
> here?

ResponseWriter is an interface so you can just wrap it. For example
https://github.com/jmckaskill/krb-httpd/blob/master/proxy.go#L678

-- James

Jackie Li

unread,
Oct 24, 2012, 12:27:16 PM10/24/12
to James McKaskill, golan...@googlegroups.com
Why I didn't think of that?

Thanks a lot!
--
Jackie

Jackie Li

unread,
Oct 24, 2012, 3:24:59 PM10/24/12
to benjami...@ai-solutions.com, golan...@googlegroups.com
That's exactly what I'm doing!

Thanks for the reply!

On Wed, Oct 24, 2012 at 4:01 PM, <benjami...@ai-solutions.com> wrote:
Add something to wrap the ResponseWriter?

type statusLoggingResponseWriter struct {
   status int
   http.ResponseWriter
}

func (w *statusLoggingResponseWriter) WriteHeader(code int) {
  w.status = code
  w.ResponseWriter.WriteHeader(code)
}

type WrapHTTPHandler struct {
m *http.Handler
}

func (h *WrapHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        myW := StatusLoggingResponseWriter{-1, w}
h.m.ServeHTTP(myW, r)
log.Printf("[%s] %s %d\n", r.RemoteAddr, r.URL, w.status)
}
--
 
 



--
Jackie
Reply all
Reply to author
Forward
0 new messages