-
Notifications
You must be signed in to change notification settings - Fork 16
/
dispatch.go
200 lines (165 loc) · 4.69 KB
/
dispatch.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
package rux
import (
"fmt"
"net"
"net/http"
"os"
"regexp"
"sort"
"strings"
)
/*************************************************************
* internal vars
*************************************************************/
// "/users/{id}" "/users/{id:\d+}" `/users/{uid:\d+}/blog/{id}`
var varRegex = regexp.MustCompile(`{[^/]+}`)
var internal404Handler HandlerFunc = func(c *Context) {
http.NotFound(c.Resp, c.Req)
}
var internal405Handler HandlerFunc = func(c *Context) {
allowed := c.SafeGet(CTXAllowedMethods).([]string)
sort.Strings(allowed)
c.SetHeader("Allow", strings.Join(allowed, ", "))
if c.Req.Method == OPTIONS {
c.SetStatus(200)
} else {
http.Error(c.Resp, "Method not allowed", 405)
}
}
/*************************************************************
* starting HTTP serve
*************************************************************/
// Listen quick create a HTTP server with the router
//
// Usage:
//
// r.Listen("8090")
// r.Listen("IP:PORT")
// r.Listen("IP", "PORT")
func (r *Router) Listen(addr ...string) {
defer func() {
debugPrintError(r.err)
}()
address := resolveAddress(addr)
fmt.Printf("Serve listen on %s. Go to http://%s\n", address, address)
r.err = http.ListenAndServe(address, r)
}
// ListenTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
func (r *Router) ListenTLS(addr, certFile, keyFile string) {
var err error
defer func() { debugPrintError(err) }()
address := resolveAddress([]string{addr})
fmt.Printf("Serve listen on %s. Go to https://%s\n", address, address)
err = http.ListenAndServeTLS(address, certFile, keyFile, r)
}
// ListenUnix attaches the router to a http.Server and starts listening and serving HTTP requests
// through the specified unix socket (i.e. a file)
func (r *Router) ListenUnix(file string) {
var err error
defer func() { debugPrintError(err) }()
fmt.Printf("Serve listen on unix:/%s\n", file)
if err = os.Remove(file); err != nil {
return
}
listener, err := net.Listen("unix", file)
if err != nil {
return
}
// defer listener.Close()
err = http.Serve(listener, r)
_ = listener.Close()
}
// WrapHTTPHandlers apply some pre http handlers for the router.
//
// Usage:
//
// import "github.com/gookit/rux/handlers"
// r := rux.New()
// // ... add routes
// handler := r.WrapHTTPHandlers(handlers.HTTPMethodOverrideHandler)
// http.ListenAndServe(":8080", handler)
func (r *Router) WrapHTTPHandlers(preHandlers ...func(h http.Handler) http.Handler) http.Handler {
var wrapped http.Handler
max := len(preHandlers)
lst := make([]int, max)
for i := range lst {
current := max - i - 1
if i == 0 {
wrapped = preHandlers[current](r)
} else {
wrapped = preHandlers[current](wrapped)
}
}
return wrapped
}
/*************************************************************
* dispatch http request
*************************************************************/
// ServeHTTP for handle HTTP request, response data to client.
func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {
// get new context
ctx := r.ctxPool.Get().(*Context)
// init and reset ctx
ctx.Init(res, req)
// handle HTTP Request
r.handleHTTPRequest(ctx)
// ctx.Reset()
// release ctx
r.ctxPool.Put(ctx)
}
// HandleContext handle a given context
func (r *Router) HandleContext(c *Context) {
c.Reset()
r.handleHTTPRequest(c)
r.ctxPool.Put(c)
}
// handle HTTP Request
func (r *Router) handleHTTPRequest(ctx *Context) {
// has panic handler
if r.OnPanic != nil {
defer func() {
if ret := recover(); ret != nil {
ctx.Set(CTXRecoverResult, ret)
r.OnPanic(ctx)
}
}()
}
path := ctx.Req.URL.Path
if r.useEncodedPath {
path = ctx.Req.URL.EscapedPath()
}
// matching route
route, params, allowed := r.QuickMatch(ctx.Req.Method, path)
var handlers HandlersChain
if route != nil { // found route
// save route params
ctx.Params = params
ctx.Set(CTXCurrentRouteName, route.name)
ctx.Set(CTXCurrentRoutePath, path)
// append main handler to last
handlers = append(route.handlers, route.handler)
} else if len(allowed) > 0 { // method not allowed
if len(r.noAllowed) == 0 {
r.noAllowed = HandlersChain{internal405Handler}
}
// add allowed methods to context
ctx.Set(CTXAllowedMethods, allowed)
handlers = r.noAllowed
} else { // not found route
if len(r.noRoute) == 0 {
r.noRoute = HandlersChain{internal404Handler}
}
handlers = r.noRoute
}
// has global middleware handlers
if len(r.handlers) > 0 {
handlers = append(r.handlers, handlers...)
}
ctx.SetHandlers(handlers)
ctx.Next() // handle processing
// has errors and has error handler
if r.OnError != nil && len(ctx.Errors) > 0 {
r.OnError(ctx)
}
ctx.writer.ensureWriteHeader()
}