Intercepting Http Response writer in Go

Sometimes we have to use http handler written by external library which we don’t want to change. It’s all fine until we need to know what the handler does, like what is the status code written to the response header.

In Go net/http it’s not possible to read the response directly for many good reason. Luckily ResponseWriter is interface!

Here is example of the interceptor, to get status code.

type HTTPResponseInterceptor struct {
	http.ResponseWriter
	StatusCode int
}

//NewHTTPResponseInterceptor create new httpInterceptor
func NewHTTPResponseInterceptor(w http.ResponseWriter) *HTTPResponseInterceptor {
	return &HTTPResponseInterceptor{w, http.StatusOK}
}

//WriteHeader override response WriteHeader
func (i *HTTPResponseInterceptor) WriteHeader(code int) {
	i.StatusCode = code
	i.ResponseWriter.WriteHeader(code)
}

The usage is pretty straight forward, wrap the writer with the one from the interceptor. Below example is how I used in my toy project, to get status code then update echo context status code.

func (i *Index) GetIndexHandler(context echo.Context) (err error) {
	i.bleveGetIndex.IndexNameLookup = func(*http.Request) string {
		return context.Param(i.indexNameLookupKey)
	}
	w := util.NewHTTPResponseInterceptor(context.Response().Writer)
	i.bleveGetIndex.ServeHTTP(w, context.Request())
	context.Response().Status = w.StatusCode

	return
}

I need 2 hours to come up with this solution, but it’s worth the time.
Quick googling give me this blog post which does exactly the same http://ndersson.me/post/capturing_status_code_in_net_http/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s