Skip to content

Instantly share code, notes, and snippets.

@kevin-cantwell
Created November 14, 2014 22:31
Show Gist options
  • Save kevin-cantwell/c28b4fc43067c0d8babb to your computer and use it in GitHub Desktop.
Save kevin-cantwell/c28b4fc43067c0d8babb to your computer and use it in GitHub Desktop.
v2 server example
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/timehop/services"
)
func main() {
s := services.NewServer()
s.Route("/identity", identityHandler).Methods("POST")
s.Start("8888")
}
var identityHandler = func() services.RequestHandler {
decoder := JSONDecoder{}
encoder := JSONEncoder{}
return services.RequestHandler{
Decoders: []services.Decoder{decoder},
Handle: func(ctx services.HttpContext) (response interface{}, err services.Error) {
var body map[string]interface{}
if err := ctx.Decoder.Decode(ctx, &body); err != nil {
return nil, err
}
return body, nil
},
Encoders: []services.Encoder{encoder},
}
}()
type JSONDecoder struct{}
func (d JSONDecoder) CanDecode(ctx services.HttpContext) bool {
ct := ctx.RequestHeader().ContentType()
return ct.Type == "application" && ct.SubType == "json"
}
func (d JSONDecoder) Decode(ctx services.HttpContext, v interface{}) services.Error {
body, err := ioutil.ReadAll(ctx.Request.Body)
if err != nil {
return services.NewError("io error", err.Error(), 2)
}
if err := json.Unmarshal(body, &v); err != nil {
return services.NewError("json unmarshal error", err.Error(), 2)
}
return nil
}
type JSONEncoder struct{}
func (e JSONEncoder) CanEncode(ctx services.HttpContext) bool {
accepts := ctx.RequestHeader().Accept()
return accepts.Type == "application" && accepts.SubType == "json"
}
func (e JSONEncoder) Encode(w http.ResponseWriter, response interface{}, svcErr services.Error) {
if svcErr != nil {
w.Header().Set(services.ThErrorIdentifier, svcErr.Type())
w.Header().Set(services.ThErrorDebugDescription, fmt.Sprint(svcErr.Code()))
w.Header().Set(services.ThErrorLocalizedDescription, svcErr.Error())
w.WriteHeader(svcErr.HttpStatus())
return
}
body, err := json.Marshal(response)
if err != nil {
servicesErr := services.NewError("json marshal error", err.Error(), 2)
w.Header().Set(services.ThErrorIdentifier, servicesErr.Type())
w.Header().Set(services.ThErrorDebugDescription, fmt.Sprint(servicesErr.Code()))
w.Header().Set(services.ThErrorLocalizedDescription, servicesErr.Error())
w.WriteHeader(servicesErr.HttpStatus())
return
}
w.Write(body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment