-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.go
269 lines (220 loc) · 6.97 KB
/
web.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package web
import (
"fmt"
"github.com/go-needle/web/log"
"html/template"
"net"
"net/http"
"path"
"strconv"
"time"
)
// Handler defines the request handler used by web
type Handler interface {
Handle(*Context)
}
// HandlerFunc realizes the Handler
type HandlerFunc func(*Context)
func (f HandlerFunc) Handle(ctx *Context) {
f(ctx)
}
type Listener interface {
Method() string
Pattern() string
Handle(*Context)
}
type GET struct{}
func (*GET) Method() string { return "GET" }
type POST struct{}
func (*POST) Method() string { return "POST" }
type DELETE struct{}
func (*DELETE) Method() string { return "DELETE" }
type PUT struct{}
func (*PUT) Method() string { return "PUT" }
type PATCH struct{}
func (*PATCH) Method() string { return "PATCH" }
type OPTIONS struct{}
func (*OPTIONS) Method() string { return "OPTIONS" }
type HEAD struct{}
func (*HEAD) Method() string { return "HEAD" }
type RouterGroup struct {
prefix string
middlewares []Handler // support middleware
parent *RouterGroup // support nesting
server *Server // all groups share a Server instance
}
// Group is defined to create a new RouterGroup
// remember all groups share the same Engine instance
func (group *RouterGroup) Group(prefix string) *RouterGroup {
if len(prefix) == 1 {
panic("the length of prefix must > 0")
}
if prefix[0] != '/' {
prefix = "/" + prefix
}
server := group.server
groupPrefix := group.prefix + prefix
newGroup := &RouterGroup{
prefix: groupPrefix,
parent: group,
server: server,
}
server.groups.insert(groupPrefix, newGroup)
return newGroup
}
func (group *RouterGroup) addRoute(method string, comp string, handler Handler) {
pattern := group.prefix + comp
group.server.router.addRoute(method, pattern, handler)
}
// Use is defined to add middleware to the group
func (group *RouterGroup) Use(middlewares ...Handler) *RouterGroup {
group.middlewares = append(group.middlewares, middlewares...)
return group
}
// Bind is defined to bind all listeners to the router
func (group *RouterGroup) Bind(listeners ...Listener) {
for _, listener := range listeners {
group.REQUEST(listener.Method(), listener.Pattern(), listener)
}
}
// REQUEST defines your method to request
func (group *RouterGroup) REQUEST(method, pattern string, handler Handler) {
if len(pattern) == 1 {
panic("the length of pattern must > 0")
}
if pattern[0] != '/' {
pattern = "/" + pattern
}
group.addRoute(method, pattern, handler)
}
// GET defines the method to add GET request
func (group *RouterGroup) GET(pattern string, handler Handler) {
group.REQUEST("GET", pattern, handler)
}
// POST defines the method to add POST request
func (group *RouterGroup) POST(pattern string, handler Handler) {
group.REQUEST("POST", pattern, handler)
}
// PUT defines the method to add PUT request
func (group *RouterGroup) PUT(pattern string, handler Handler) {
group.REQUEST("PUT", pattern, handler)
}
// DELETE defines the method to add DELETE request
func (group *RouterGroup) DELETE(pattern string, handler Handler) {
group.REQUEST("DELETE", pattern, handler)
}
// PATCH defines the method to add PATCH request
func (group *RouterGroup) PATCH(pattern string, handler Handler) {
group.REQUEST("PATCH", pattern, handler)
}
// OPTIONS defines the method to add OPTIONS request
func (group *RouterGroup) OPTIONS(pattern string, handler Handler) {
group.REQUEST("OPTIONS", pattern, handler)
}
// HEAD defines the method to add HEAD request
func (group *RouterGroup) HEAD(pattern string, handler Handler) {
group.REQUEST("HEAD", pattern, handler)
}
// create static handler
func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) Handler {
absolutePath := path.Join(group.prefix, relativePath)
fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
return HandlerFunc(func(c *Context) {
file := c.Param("filepath")
// Check if file exists and/or if we have permission to access it
if _, err := fs.Open(file); err != nil {
c.Fail(http.StatusNotFound, err.Error())
return
}
fileServer.ServeHTTP(c.Writer, c.Request)
})
}
// Static is defined to map local static resources
func (group *RouterGroup) Static(relativePath string, root string) {
handler := group.createStaticHandler(relativePath, http.Dir(root))
urlPattern := path.Join(relativePath, "/*filepath")
// Register GET handlers
group.GET(urlPattern, handler)
}
type Server struct {
*RouterGroup
router *router
groups *trieTreeG // store all groups
htmlTemplates *template.Template // for html render
funcMap template.FuncMap // for html render
}
func newServer() *Server {
server := &Server{router: newRouter()}
server.RouterGroup = &RouterGroup{server: server}
server.groups = newTrieTreeG(server.RouterGroup)
return server
}
// New is the constructor of web.Server
func New() *Server {
return newServer()
}
// Default is the constructor of web.Server with Recovery and Logger
func Default() *Server {
server := newServer()
server.Use(Recovery(), Logger())
return server
}
// Use is defined to add middleware to the server
func (server *Server) Use(middlewares ...Handler) *Server {
server.middlewares = append(server.middlewares, middlewares...)
return server
}
func (server *Server) SetFuncMap(funcMap template.FuncMap) {
server.funcMap = funcMap
}
func (server *Server) LoadHTMLGlob(pattern string) {
server.htmlTemplates = template.Must(template.New("").Funcs(server.funcMap).ParseGlob(pattern))
}
// Engine implement the interface of ServeHTTP
type Engine struct {
server *Server
}
func getInternalIP() (string, error) {
adders, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, address := range adders {
if ip, ok := address.(*net.IPNet); ok && !ip.IP.IsLoopback() {
if ip.IP.To4() != nil {
return ip.IP.String(), nil
}
}
}
return "", fmt.Errorf("no internal IP address found, check for multiple interfaces")
}
func welcome(routerNum int) {
time.Sleep(time.Millisecond * 100)
log.Info("🪡 Welcome to use go-needle-web")
log.Info("🪡 Available router total: " + strconv.Itoa(routerNum))
ip, err := getInternalIP()
if err == nil {
log.Info("🪡 IP address: " + ip)
}
}
// Run defines the method to start a http server
func (server *Server) Run(port int) {
portStr := strconv.Itoa(port)
welcome(server.router.total)
log.Info("🪡 The http server is listening at port " + portStr)
log.Fatal(http.ListenAndServe(":"+portStr, &Engine{server}))
}
// RunTLS defines the method to start a https server
func (server *Server) RunTLS(port int, certFile, keyFile string) {
portStr := strconv.Itoa(port)
welcome(server.router.total)
log.Info("🪡 The https server is listening at port " + portStr)
log.Fatal(http.ListenAndServeTLS(":"+portStr, certFile, keyFile, &Engine{server}))
}
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
middlewaresFind := engine.server.groups.search(req.URL.Path)
c := newContext(w, req)
c.handlers = middlewaresFind
c.server = engine.server
engine.server.router.handle(c)
}