diff options
Diffstat (limited to 'core.go')
-rw-r--r-- | core.go | 80 |
1 files changed, 59 insertions, 21 deletions
@@ -1,14 +1,24 @@ package sleepy import ( + "encoding/json" + "fmt" "net/http" + "net/url" +) + +const ( + GET = "GET" + POST = "POST" + PUT = "PUT" + DELETE = "DELETE" ) type Resource interface { - Get(map[string][]string) string - Post(map[string][]string) string - Put(map[string][]string) string - Delete(map[string][]string) string + Get(values ...url.Values) (int, interface{}) + Post(values ...url.Values) (int, interface{}) + Put(values ...url.Values) (int, interface{}) + Delete(values ...url.Values) (int, interface{}) } type Route struct { @@ -33,27 +43,55 @@ func (api *Api) matchResource(path string) Resource { return nil } -func (api *Api) dispatchRequest(request *http.Request, resource Resource) string { - method := request.Method +func (api *Api) Abort(statusCode int) (int, interface{}) { + return statusCode, map[string]string{"error": "Aborted."} +} + +type HandleFunc func(http.ResponseWriter, *http.Request) + +func (api *Api) requestHandler(resource Resource) HandleFunc { + return func(rw http.ResponseWriter, request *http.Request) { + + var code int + var data interface{} + var content []byte + + method := request.Method + + if request.ParseForm() == nil { + code, data = api.Abort(500) + } + + values := request.Form + + switch method { + case GET: + code, data = resource.Get(values) + case POST: + code, data = resource.Post(values) + case PUT: + code, data = resource.Put(values) + case DELETE: + code, data = resource.Delete(values) + default: + code, data = 405, map[string]string{"error": "Not implemented!"} + } - switch method { - case "GET": - return resource.Get(nil) - case "POST": - return resource.Post(nil) - case "PUT": - return resource.Put(nil) - case "DELETE": - return resource.Delete(nil) + content, err := json.Marshal(data) + if err != nil { + content, _ = json.Marshal(map[string]string{"error": "Bad response."}) + } + + rw.WriteHeader(code) + rw.Write(content) } - return "Not implemented!" } -func (api *Api) HandleRequest(request *http.Request) string { - resource := api.matchResource(request.URL.Path) - return api.dispatchRequest(request, resource) +func (api *Api) AddResource(resource Resource, path string) { + http.HandleFunc(path, api.requestHandler(resource)) } -func (api *Api) AddResource(resource Resource, path string) { - api.routes = append(api.routes, Route{resource, path}) +func (api *Api) Start(port int) { + portString := fmt.Sprintf(":%d", port) + http.ListenAndServe(portString, nil) } |