Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"bytes"
"encoding/json"
"encoding/xml"
"github.com/go-martini/martini"
"net/http"
"reflect"
"time"
)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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")
}
}