aboutsummaryrefslogtreecommitdiffstats
path: root/torpedo.go
diff options
context:
space:
mode:
authorDavid Hurst2016-04-17 11:57:44 -0600
committerDavid Hurst2016-04-17 11:57:44 -0600
commit353a3b7151ba1f059bc0275fabf11ca049e7cb52 (patch)
tree9f25ae9576a253376d572167b3de552ee912e728 /torpedo.go
parent0385b1081aab533fce98f5ec1dd9b8d476d65581 (diff)
downloadtorpedo-353a3b7151ba1f059bc0275fabf11ca049e7cb52.tar.gz
torpedo-353a3b7151ba1f059bc0275fabf11ca049e7cb52.zip
Updated structure/readme
Diffstat (limited to 'torpedo.go')
-rw-r--r--torpedo.go88
1 files changed, 88 insertions, 0 deletions
diff --git a/torpedo.go b/torpedo.go
new file mode 100644
index 0000000..e0c1b99
--- /dev/null
+++ b/torpedo.go
@@ -0,0 +1,88 @@
1package torpedo
2
3import (
4 "fmt"
5 "net/http"
6 "net/url"
7)
8
9const (
10 GET = "GET"
11 POST = "POST"
12 PUT = "PUT"
13 DELETE = "DELETE"
14)
15
16type Resource interface {
17 Get(values url.Values) (int, string)
18 Post(values url.Values) (int, string)
19 Put(values url.Values) (int, string)
20 Delete(values url.Values) (int, string)
21}
22
23type (
24 GetNotSupported struct{}
25 PostNotSupported struct{}
26 PutNotSupported struct{}
27 DeleteNotSupported struct{}
28)
29
30func (GetNotSupported) Get(values url.Values) (int, string) {
31 return 405, ""
32}
33
34func (PostNotSupported) Post(values url.Values) (int, string) {
35 return 405, ""
36}
37
38func (PutNotSupported) Put(values url.Values) (int, string) {
39 return 405, ""
40}
41
42func (DeleteNotSupported) Delete(values url.Values) (int, string) {
43 return 405, ""
44}
45
46type API struct{}
47
48func (api *API) Abort(rw http.ResponseWriter, statusCode int) {
49 rw.WriteHeader(statusCode)
50}
51
52func (api *API) requestHandler(resource Resource) http.HandlerFunc {
53 return func(rw http.ResponseWriter, request *http.Request) {
54
55 var data string
56 var code int
57
58 request.ParseForm()
59 method := request.Method
60 values := request.Form
61
62 switch method {
63 case GET:
64 code, data = resource.Get(values)
65 case POST:
66 code, data = resource.Post(values)
67 case PUT:
68 code, data = resource.Put(values)
69 case DELETE:
70 code, data = resource.Delete(values)
71 default:
72 api.Abort(rw, 405)
73 return
74 }
75
76 rw.WriteHeader(code)
77 rw.Write([]byte(data))
78 }
79}
80
81func (api *API) AddResource(resource Resource, path string) {
82 http.HandleFunc(path, api.requestHandler(resource))
83}
84
85func (api *API) Start(port int) {
86 portString := fmt.Sprintf(":%d", port)
87 http.ListenAndServe(portString, nil)
88}