From da9d8e922d0198a324af1f1b6df97d3e1d5938aa Mon Sep 17 00:00:00 2001 From: Karan Misra Date: Mon, 27 Jan 2014 10:54:05 +0530 Subject: remove the need to provide “missing/unsupported” implementations in the API consumers. also: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - more idiomatic - loosely coupled with the API contract --- core.go | 47 +++++++++++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 16 deletions(-) (limited to 'core.go') diff --git a/core.go b/core.go index c8d7ca9..bbcb009 100644 --- a/core.go +++ b/core.go @@ -14,10 +14,19 @@ const ( DELETE = "DELETE" ) -type Resource interface { +type geter interface { Get(values url.Values) (int, interface{}) +} + +type poster interface { Post(values url.Values) (int, interface{}) +} + +type puter interface { Put(values url.Values) (int, interface{}) +} + +type deleter interface { Delete(values url.Values) (int, interface{}) } @@ -27,12 +36,8 @@ func (api *Api) Abort(rw http.ResponseWriter, statusCode int) { rw.WriteHeader(statusCode) } -func (api *Api) requestHandler(resource Resource) http.HandlerFunc { +func (api *Api) requestHandler(resource interface{}) http.HandlerFunc { return func(rw http.ResponseWriter, request *http.Request) { - - var data interface{} - var code int - method := request.Method if request.ParseForm() != nil { api.Abort(rw, 400) @@ -40,35 +45,45 @@ func (api *Api) requestHandler(resource Resource) http.HandlerFunc { } values := request.Form + var data interface{} = "" + var code int = 405 + switch method { case GET: - code, data = resource.Get(values) + if r, ok := resource.(geter); ok { + code, data = r.Get(values) + } case POST: - code, data = resource.Post(values) + if r, ok := resource.(poster); ok { + code, data = r.Post(values) + } case PUT: - code, data = resource.Put(values) + if r, ok := resource.(puter); ok { + code, data = r.Put(values) + } case DELETE: - code, data = resource.Delete(values) + if r, ok := resource.(deleter); ok { + code, data = r.Delete(values) + } default: api.Abort(rw, 405) return } - responseWriter := json.NewEncoder(rw) + responseWriter := json.NewEncoder(rw) rw.WriteHeader(code) if responseWriter.Encode(data) != nil { - api.Abort(rw, 500) - return - } + api.Abort(rw, 500) + return + } } } -func (api *Api) AddResource(resource Resource, path string) { +func (api *Api) AddResource(resource interface{}, path string) { http.HandleFunc(path, api.requestHandler(resource)) } func (api *Api) Start(port int) { portString := fmt.Sprintf(":%d", port) http.ListenAndServe(portString, nil) - fmt.Println("Hi.") } -- cgit