Skip to content

Instantly share code, notes, and snippets.

@jamiecuthill
Last active December 2, 2015 10:09
Show Gist options
  • Save jamiecuthill/b35110897bfd3d366c77 to your computer and use it in GitHub Desktop.
Save jamiecuthill/b35110897bfd3d366c77 to your computer and use it in GitHub Desktop.
http json encoding errors
package main
import (
"encoding/json"
)
type ErrorType struct {
Title string `json:"title"`
Detail string `json:"detail"`
Code int `json:"code"`
Status int
}
func (e ErrorType) Error() string {
return e.Title
}
func (e ErrorType) toJSON() ([]byte, error) {
return json.Marshal(e)
}
func Must(data []byte, err error) []byte {
if err != nil {
panic(err)
}
return data
}
func main() {
err := ErrorType{"foo", "bar", 1000, 500}
http.Error(httptest.NewRecorder(), Must(err.toJSON()), err.Status)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment