diff options
Diffstat (limited to 'core.go')
-rw-r--r-- | core.go | 32 |
1 files changed, 21 insertions, 11 deletions
@@ -30,13 +30,16 @@ type deleter interface { Delete(values url.Values) (int, interface{}) } -type Api struct{} +type API struct { + mux *http.ServeMux +} -func (api *Api) Abort(rw http.ResponseWriter, statusCode int) { +func (api *API) Abort(rw http.ResponseWriter, statusCode int) { rw.WriteHeader(statusCode) + rw.Write([]byte(http.StatusText(statusCode))) } -func (api *Api) requestHandler(resource interface{}) http.HandlerFunc { +func (api *API) requestHandler(resource interface{}) http.HandlerFunc { return func(rw http.ResponseWriter, request *http.Request) { method := request.Method if request.ParseForm() != nil { @@ -70,20 +73,27 @@ func (api *Api) requestHandler(resource interface{}) http.HandlerFunc { return } - responseWriter := json.NewEncoder(rw) - rw.WriteHeader(code) - if responseWriter.Encode(data) != nil { + content, err := json.Marshal(data) + if err != nil { api.Abort(rw, 500) - return } + rw.WriteHeader(code) + rw.Write(content) } } -func (api *Api) AddResource(resource interface{}, path string) { - http.HandleFunc(path, api.requestHandler(resource)) +func (api *API) AddResource(resource interface{}, path string) { + if api.mux == nil { + api.mux = http.NewServeMux() + } + api.mux.HandleFunc(path, api.requestHandler(resource)) } -func (api *Api) Start(port int) { +func (api *API) Start(port int) error { + if api.mux == nil { + return &errorString{"You must add at last one resource to this API."} + } portString := fmt.Sprintf(":%d", port) - http.ListenAndServe(portString, nil) + http.ListenAndServe(portString, api.mux) + return nil } |