Skip to content

Instantly share code, notes, and snippets.

@kisielk
Created February 15, 2013 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kisielk/4961615 to your computer and use it in GitHub Desktop.
Save kisielk/4961615 to your computer and use it in GitHub Desktop.
Simple HTTP handler wrapper for conveniently dealing with JSON requests
// JSONResponseWriter wraps an http.ResponseWriter and provides convenience methods for creating JSON responses
type JSONResponseWriter struct {
writer http.ResponseWriter
}
// Response writes an HTTP response with the value v encoded in JSON format.
func (w JSONResponseWriter) Response(v interface{}) {
w.writer.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w.writer)
enc.Encode(v)
}
// Response returns an HTTP response with the given status code and a message encoded in JSON format.
// The format and args arguments are analagous to those in fmt.Printf. The resulting JSON is an object with
// a single field "error", eg:
//
// {"error": "some message"}
//
func (w JSONResponseWriter) Error(code int, format string, args ...interface{}) {
type Error struct {
Error string `json:"error"`
}
w.writer.Header().Set("Content-Type", "application/json")
msg := Error{fmt.Sprintf(format, args...)}
w.writer.WriteHeader(code)
enc := json.NewEncoder(w.writer)
// Nothing we can do about errors at this point, so ignore them
enc.Encode(msg)
}
// JSONRequest is a wrapper around http.Request that provides additional methods for dealing with requests
// that contain JSON-encoded content
type JSONRequest struct {
*http.Request
}
// Decode reads the JSON-encoded value from the request body and stores it in the value pointed to by v.
func (r JSONRequest) Decode(v interface{}) error {
dec := json.NewDecoder(r.Body)
return dec.Decode(v)
}
// JSONHandler is a type of handler for JSON-encoded HTTP requests
type JSONHandler func(w JSONResponseWriter, r JSONRequest)
func (h JSONHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h(JSONResponseWriter{w}, JSONRequest{r})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment