diff --git a/encoder.go b/encoder.go index d6bed5f..f0e8495 100644 --- a/encoder.go +++ b/encoder.go @@ -9,6 +9,8 @@ import ( "bytes" "encoding/json" "encoding/xml" + "github.com/go-martini/martini" + "net/http" "reflect" "time" ) @@ -17,6 +19,7 @@ import ( // requests on the API endpoints. type Encoder interface { Encode(v ...interface{}) ([]byte, error) + Render(v ...interface{}) []byte } // Because `panic`s are caught by martini's Recovery handler, it can be used @@ -63,6 +66,10 @@ func (_ JsonEncoder) Encode(v ...interface{}) ([]byte, error) { return json.Marshal(result) } +func (enc JsonEncoder) Render(v ...interface{}) []byte { + return Must(enc.Encode(v...)) +} + type XmlEncoder struct{} // Since we don't use xml as a binding source, we don't need to use @@ -91,6 +98,10 @@ func (_ XmlEncoder) Encode(v ...interface{}) ([]byte, error) { return buffer.Bytes(), nil } +func (enc XmlEncoder) Render(v ...interface{}) []byte { + return Must(enc.Encode(v...)) +} + func copyStruct(v reflect.Value) reflect.Value { if v.Kind() == reflect.Ptr { v = v.Elem() @@ -158,3 +169,17 @@ func iterateSlice(v reflect.Value) reflect.Value { return result } + +func JSON() func(martini.Context, http.ResponseWriter) { + return func(c martini.Context, w http.ResponseWriter) { + c.MapTo(JsonEncoder{}, (*Encoder)(nil)) + w.Header().Set("Content-Type", "application/json; charset=utf-8") + } +} + +func XML() func(martini.Context, http.ResponseWriter) { + return func(c martini.Context, w http.ResponseWriter) { + c.MapTo(XmlEncoder{}, (*Encoder)(nil)) + w.Header().Set("Content-Type", "application/xml; charset=utf-8") + } +}