blob: 3ef4029cbfe093b7caa2df11d9a2be8a5aba3497 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
package sleepy
import (
"net/http"
)
type Resource interface {
Get(p [string][]string) string
Post(map[string][]string) string
Put(map[string][]string) string
Delete(map[string][]string) string
}
type GetNotSupported struct{}
func (GetNotSupported) Get(map[string][]string) string {
return "Nope."
}
type PostNotSupported struct{}
func (PostNotSupported) Post(map[string][]string) string {
return "Nope."
}
type PutNotSupported struct{}
func (PutNotSupported) Put(map[string][]string) string {
return "Nope."
}
type DeleteNotSupported struct{}
func (DeleteNotSupported) Delete(map[string][]string) string {
return "Nope."
}
type Route struct {
resource Resource
path string
}
func (route *Route) pathMatch(path string) bool {
return route.path == path
}
type Api struct {
routes []Route
}
func (api *Api) matchResource(path string) Resource {
for _, route := range api.routes {
if route.pathMatch(path) {
return route.resource
}
}
return nil
}
func (api *Api) dispatchRequest(request *http.Request, resource Resource) string {
method := request.Method
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)
}
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) {
api.routes = append(api.routes, Route{resource, path})
}
|