This repository has been archived by the owner on Jun 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
router.go
206 lines (182 loc) · 5.08 KB
/
router.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package web
import (
"errors"
"fmt"
"net/http"
pathlib "path"
"strconv"
"strings"
"path"
"github.com/go-zepto/zepto/web/renderer"
"github.com/gorilla/mux"
)
type routerOptions struct {
path string
hosts []string
isRoot bool
}
type RouterHandler struct {
methods []string
path string
routeHandler RouteHandler
}
type Router struct {
options routerOptions
handlers []RouterHandler
middleware MiddlewareStack
}
func NewRouter(path string, opts ...RouterOption) *Router {
options := newRouterOptions(path, opts...)
router := Router{
handlers: make([]RouterHandler, 0),
options: options,
middleware: MiddlewareStack{
stack: make([]MiddlewareFunc, 0),
skips: nil,
},
}
return &router
}
type RouterOption func(*routerOptions)
func Hosts(hosts ...string) RouterOption {
return func(o *routerOptions) {
o.hosts = hosts
}
}
func newRouterOptions(path string, opts ...RouterOption) routerOptions {
opt := routerOptions{
path: path,
}
for _, o := range opts {
o(&opt)
}
return opt
}
func (app *App) Router(path string, opts ...RouterOption) *Router {
router := NewRouter(path, opts...)
app.routers = append(app.routers, router)
return router
}
func (router *Router) HandleMethod(methods []string, path string, routeHandler RouteHandler) *Router {
gh := RouterHandler{
methods: methods,
path: path,
routeHandler: routeHandler,
}
router.handlers = append(router.handlers, gh)
return router
}
func (router *Router) Get(path string, routeHandler RouteHandler) *Router {
return router.HandleMethod([]string{"GET", "OPTIONS"}, path, routeHandler)
}
func (router *Router) Post(path string, routeHandler RouteHandler) *Router {
return router.HandleMethod([]string{"POST", "OPTIONS"}, path, routeHandler)
}
func (router *Router) Put(path string, routeHandler RouteHandler) *Router {
return router.HandleMethod([]string{"PUT", "OPTIONS"}, path, routeHandler)
}
func (router *Router) Delete(path string, routeHandler RouteHandler) *Router {
return router.HandleMethod([]string{"DELETE", "OPTIONS"}, path, routeHandler)
}
func (router *Router) Patch(path string, routeHandler RouteHandler) *Router {
return router.HandleMethod([]string{"PATCH", "OPTIONS"}, path, routeHandler)
}
func (router *Router) Any(path string, routeHandler RouteHandler) *Router {
return router.HandleMethod([]string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}, path, routeHandler)
}
func (router *Router) Use(mw ...MiddlewareFunc) {
router.middleware.Use(mw...)
}
func (router *Router) UsePrepend(mw ...MiddlewareFunc) {
router.middleware.UsePrepend(mw...)
}
func (router *Router) Resource(path string, resource Resource) *Router {
id_path := pathlib.Join(path, "/{id}")
router.Get(path, resource.List)
router.Get(id_path, resource.Show)
router.Post(path, resource.Create)
router.Put(id_path, resource.Update)
router.Delete(id_path, resource.Destroy)
return router
}
// HandleError recovers from panics gracefully and calls
func (app *App) HandleError(router *Router, ctx Context, err error) {
status := ctx.GetStatus()
if status == 200 {
status = 500
}
ctx.Response().WriteHeader(status)
errMessage := strings.ToLower(strconv.Itoa(status) + " - " + http.StatusText(status))
if err != nil && app.isDev() {
errMessage = errMessage + ": " + err.Error()
renderer.RenderDevelopmentError(ctx.Response(), ctx.Request(), errors.New(errMessage))
return
}
ctx.Response().Write([]byte(errMessage))
}
func (app *App) registerRouterHandleFunc(router *Router, h RouterHandler, host *string) {
var muxRouter *mux.Router
if host == nil {
muxRouter = app.muxRouter
} else {
muxRouter = app.muxRouter.Host(*host).Subrouter()
}
routerPath := router.options.path
muxRouter.HandleFunc(path.Join(routerPath, h.path), func(res http.ResponseWriter, req *http.Request) {
ctx := NewDefaultContext()
ctx.logger = app.opts.logger
ctx.res = res
ctx.req = req
ctx.db = app.opts.db
ctx.cookies = &Cookies{
res: res,
req: req,
}
ctx.session = app.getSession(res, req)
ctx.tmplEngine = app.tmplEngine
ctx.pluginsInstances = app.opts.pluginInstances
// Handle Controller Panic
defer func() {
if r := recover(); r != nil {
var e error
switch t := r.(type) {
case error:
e = t
case string:
e = fmt.Errorf(t)
default:
e = fmt.Errorf(fmt.Sprint(t))
}
app.HandleError(router, ctx, e)
}
}()
h := h.routeHandler
// Middlewares
mwStack := MiddlewareStack{
stack: make([]MiddlewareFunc, 0),
}
// Apply Root Middlewares
if router != app.rootRouter {
mwStack.Use(app.rootRouter.middleware.stack...)
}
mwStack.Use(router.middleware.stack...)
// Apply Middleware Stack
h = mwStack.handle(h)
err := h(ctx)
// Handle Controller Error
if err != nil {
app.HandleError(router, ctx, err)
}
}).Methods(h.methods...)
}
func (app *App) initRouterHandlers(router *Router) {
for _, h := range router.handlers {
if len(router.options.hosts) == 0 {
app.registerRouterHandleFunc(router, h, nil)
} else {
for _, host := range router.options.hosts {
app.registerRouterHandleFunc(router, h, &host)
}
}
}
}