/
registrar.go
87 lines (71 loc) · 2.26 KB
/
registrar.go
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
84
85
86
87
package balaur
import (
"fmt"
"net/http"
"reflect"
"github.com/sendyhalim/balaur/context"
"github.com/zenazn/goji/web"
)
type ControllerMethod func(context.ContextInterface, *http.Request) (string, int)
type RouteRegistrar interface {
RegisterRoutes(*web.Mux, []Config, map[string]interface{})
}
type MiddlewareRegistrar interface {
RegisterMiddlewares(*web.Mux, []Config, map[string]interface{})
}
type BasicRouteRegistrar struct {
ControllerMethodWrapper func(ControllerMethod) web.HandlerFunc
}
func (r *BasicRouteRegistrar) RegisterRoutes(mux *web.Mux, routes []Config, controllers map[string]interface{}) {
for _, config := range routes {
controller := config.Get("controller", true)
method := config.Get("method", true)
verb := config.Get("verb", true)
path := config.Get("path", true)
methodInterface := reflect.ValueOf(controllers[controller]).MethodByName(method).Interface()
methodValue := methodInterface.(func(context.ContextInterface, *http.Request) (string, int))
handler := r.ControllerMethodWrapper(methodValue)
switch verb {
case "GET":
mux.Get(path, handler)
case "POST":
mux.Post(path, handler)
case "PUT":
mux.Put(path, handler)
case "DELETE":
mux.Delete(path, handler)
}
}
}
type BasicMiddlewareRegistrar struct {
}
func (r *BasicMiddlewareRegistrar) RegisterMiddlewares(mux *web.Mux, middlewareConfigs []Config, middlewares map[string]interface{}) {
for _, m := range middlewareConfigs {
key := m.Get("key", true)
mux.Use(middlewares[key])
}
}
func NewBasicMiddlewareRegistrar() *BasicMiddlewareRegistrar {
return &BasicMiddlewareRegistrar{}
}
func NewBasicRouteRegistrar() *BasicRouteRegistrar {
r := &BasicRouteRegistrar{}
// basic controller method wrapper
r.ControllerMethodWrapper = func(method ControllerMethod) web.HandlerFunc {
fn := func(c web.C, w http.ResponseWriter, r *http.Request) {
c.Env["Content-Type"] = "text/html"
response, code := method(&context.GojiContext{C: &c}, r)
switch code {
case http.StatusOK:
if _, exists := c.Env["Content-Type"]; exists {
w.Header().Set("Content-Type", c.Env["Content-Type"].(string))
}
fmt.Fprint(w, response)
case http.StatusSeeOther:
http.Redirect(w, r, response, code)
}
}
return web.HandlerFunc(fn)
}
return r
}