Repository navigation
Expand file tree
/
Copy pathapplication.go
More file actions
648 lines (560 loc) · 17.6 KB
/
Copy pathapplication.go
File metadata and controls
648 lines (560 loc) · 17.6 KB
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package pine
import (
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"sync"
gomime "github.com/cubewise-code/go-mime"
"github.com/xiusin/pine/di"
"log/slog"
)
// Version 框架版本号.
const Version = "dev-master"
// logo 启动 logo.
const logo = `
____ _
| _ \(_)_ __ ___
| |_) | | '_ \ / _ \
| __/| | | | | __/
|_| |_|_| |_|\___|`
// FilePathParam 静态路由 filepath 参数名.
const FilePathParam = "filepath"
var (
urlSeparator = "/"
// 记录匹配路由映射, 不管是分组还是非分组的正则路由均记录到此变量
patternRoutes = map[string][]*RouteEntry{}
// 按照注册顺序保存匹配路由内容, 防止 map 迭代出现随机匹配的情况
sortedPattern []string
// 正则路由特征匹配
patternRouteCompiler = regexp.MustCompile(`[:*](\w[A-Za-z0-9_/]+)(<.+?>)?`)
// 内置替换规则 (后面改写为拦截器)
patternMap = map[string]string{
":int": "<\\d+>",
":string": "<.+>",
":any": "<.*>",
}
// patternRegexpCache 缓存编译后的正则, 避免每次请求重新编译 (优化点).
patternRegexpCache = map[string]*regexp.Regexp{}
patternRegexpMu sync.RWMutex
controllerDefaultAction = ""
_ AbstractRouter = (*Application)(nil)
)
// RouteEntry 路由条目.
// ExtendsMiddleWare 在注册时一次性设置, 避免运行时并发写入 (resolved 字段已移除).
type RouteEntry struct {
Method string
Middleware []Handler
ExtendsMiddleWare []Handler
Handle Handler
HandlerName string
Param []string
Pattern string
}
// AbstractRouter 路由抽象接口.
type AbstractRouter interface {
AddRoute(method, path string, handle Handler, mws ...Handler)
ANY(path string, handle Handler, mws ...Handler)
GET(path string, handle Handler, mws ...Handler)
POST(path string, handle Handler, mws ...Handler)
HEAD(path string, handle Handler, mws ...Handler)
PUT(path string, handle Handler, mws ...Handler)
DELETE(path string, handle Handler, mws ...Handler)
StaticFile(string, string, ...Handler)
Static(string, string)
}
// IRegisterHandler 可注册路由的控制器接口.
type IRegisterHandler interface {
RegisterRoute(IRouterWrapper)
}
type routeMaker func(path string, handle Handler, mws ...Handler)
// Handler 请求处理函数签名.
type Handler func(ctx *Context)
type routerMap map[string]map[string]*RouteEntry
// Router 路由器.
type Router struct {
prefix string
methodRoutes routerMap
middleWares []Handler
groups map[string]*Router
registeredSubdomains map[string]*Router
subdomain string
hostname string
}
// Application 应用实例.
type Application struct {
*Router
pool sync.Pool
DI di.AbstractBuilder
quitCh chan os.Signal
recoverHandler Handler
configuration *Configuration
ReadonlyConfiguration ReadonlyConfiguration
}
func init() {
di.Instance(slog.Default())
}
// New 创建应用实例.
func New() *Application {
app := &Application{
Router: &Router{
methodRoutes: initRouteEntity(),
groups: map[string]*Router{},
registeredSubdomains: map[string]*Router{},
},
configuration: &Configuration{},
DI: di.GetDefaultDI(),
recoverHandler: defaultRecoverHandler,
}
app.pool.New = func() any { return newContext(app) }
app.SetNotFound(func(c *Context) {
if len(c.Msg) == 0 {
c.Msg = http.StatusText(http.StatusNotFound)
}
c.Response.Header().Set(HeaderContentType, ContentTypeHTML)
_ = DefaultErrTemplate.Execute(c.Response.BodyWriter(), H{"Message": c.Msg, "Code": http.StatusNotFound})
})
app.NotAllowMethod(func(c *Context) {
if len(c.Msg) == 0 {
c.Msg = http.StatusText(http.StatusForbidden)
}
c.Response.Header().Set(HeaderContentType, ContentTypeHTML)
_ = DefaultErrTemplate.Execute(c.Response.BodyWriter(), H{"Message": c.Msg, "Code": http.StatusMethodNotAllowed})
})
di.Instance(app)
return app
}
func (r *Router) register(controller IController, prefix ...string) {
wrapper := newRouterWrapper(r, controller)
if len(prefix) == 0 {
prefix = append(prefix, "")
}
if v, implemented := any(controller).(IRegisterHandler); implemented {
v.RegisterRoute(wrapper)
} else {
val, typ := reflect.ValueOf(controller), reflect.TypeOf(controller)
num, routeWrapper := typ.NumMethod(), wrapper
if len(controllerDefaultAction) > 0 {
r.matchRegister(controllerDefaultAction, prefix[0], routeWrapper.warpHandler(controllerDefaultAction, controller))
r.ANY(prefix[0], routeWrapper.warpHandler(controllerDefaultAction, controller))
}
for i := 0; i < num; i++ {
name := typ.Method(i).Name
if len(controllerDefaultAction) > 0 && name == controllerDefaultAction {
continue
}
if _, ok := reflectingNeedIgnoreMethods[name]; !ok && val.MethodByName(name).IsValid() {
r.matchRegister(name, prefix[0], routeWrapper.warpHandler(name, controller))
}
}
// 不再置 nil reflectingNeedIgnoreMethods, 允许多个 controller 注册时复用忽略列表
}
}
func (r *Router) matchRegister(path, prefix string, handle Handler) {
var methods = map[string]routeMaker{
"Get": r.GET,
"Put": r.PUT,
"Post": r.POST,
"Head": r.HEAD,
"Delete": r.DELETE,
}
for method, routeMaker := range methods {
if strings.HasPrefix(path, method) {
route := fmt.Sprintf("%s%s%s", prefix, urlSeparator, upperCharToUnderLine(strings.TrimPrefix(path, method)))
routeMaker(route, handle)
}
}
}
// Subdomain 创建子域名路由.
func (r *Router) Subdomain(subdomain string) *Router {
s := &Router{
// 浅拷贝父级中间件, 避免子域 Use 影响父域 (与 Group 行为一致)
middleWares: append([]Handler(nil), r.middleWares...),
groups: map[string]*Router{},
registeredSubdomains: r.registeredSubdomains,
}
s.methodRoutes = initRouteEntity()
s.subdomain = subdomain + r.subdomain
r.registeredSubdomains[s.subdomain] = s
return s
}
// SetRecoverHandler 设置 panic 恢复处理器.
func (a *Application) SetRecoverHandler(handler Handler) {
a.recoverHandler = handler
}
// SetNotFound 设置 404 处理器.
func (a *Application) SetNotFound(handler Handler) {
codeCallHandler[http.StatusNotFound] = handler
}
// NotAllowMethod 设置不允许方法处理器.
func (a *Application) NotAllowMethod(handler Handler) {
codeCallHandler[http.StatusMethodNotAllowed] = handler
}
// Close 关闭应用, 发送中断信号触发优雅关闭.
func (a *Application) Close() {
if a.quitCh != nil {
select {
case a.quitCh <- os.Interrupt:
default:
}
}
}
// handle 处理请求.
func (a *Application) handle(c *Context) {
if route := a.matchRoute(c); route != nil {
c.setRoute(route)
defer func() {
if c.sess != nil {
_ = c.sess.Save()
}
}()
c.Next()
} else {
if handler, ok := codeCallHandler[http.StatusNotFound]; ok {
c.SetStatus(http.StatusNotFound)
c.setRoute(&RouteEntry{
ExtendsMiddleWare: a.middleWares,
Handle: handler,
}).Next()
} else {
panic(c.Msg)
}
}
}
// Run 启动应用.
func (a *Application) Run(srv ServerHandler, opts ...Configurator) {
if srv == nil {
panic(errors.New("server handler can't nil."))
}
if len(opts) > 0 {
for _, opt := range opts {
opt(a.configuration)
}
}
a.ReadonlyConfiguration = a.configuration
if err := srv(a); err != nil && err != http.ErrServerClosed {
// http.ErrServerClosed 是优雅关闭的正常返回, 不应 panic
panic(err)
}
}
// Handle 注册控制器路由.
func (r *Router) Handle(c IController, prefix ...string) *Router {
r.register(c, prefix...)
return r
}
// AddRoute 添加路由.
func (r *Router) AddRoute(method, path string, handle Handler, mws ...Handler) {
var (
params []string
pattern string
)
if len(path) == 0 {
panic(errors.New("path can not empty."))
}
if strings.Count(path, "*") > 1 {
panic(errors.New("optional parameters can only be one."))
}
for patternType, patternString := range patternMap {
path = strings.Replace(path, patternType, patternString, -1)
}
fullPath := strings.TrimRight(r.prefix+path, urlSeparator)
if isPattern, _ := regexp.MatchString("[:*]", fullPath); isPattern {
uriPartials := strings.Split(fullPath, urlSeparator)[1:]
for _, v := range uriPartials {
if strings.Contains(v, ":") {
pattern = pattern + urlSeparator + patternRouteCompiler.ReplaceAllStringFunc(v, func(s string) string {
param, patternStr := r.getPattern(s, false)
params = append(params, param)
return patternStr
})
} else if strings.HasPrefix(v, "*") {
param, patternStr := r.getPattern(v, true)
pattern = fmt.Sprintf("%s%s?%s?", pattern, urlSeparator, patternStr)
params = append(params, param)
} else {
pattern = pattern + urlSeparator + v
}
}
pattern = fmt.Sprintf("^%s$", pattern)
}
route := &RouteEntry{
Method: method,
Handle: handle,
Middleware: mws,
ExtendsMiddleWare: r.middleWares, // 注册时一次性设置, 避免运行时并发写入
Param: params,
Pattern: pattern,
}
if len(pattern) != 0 {
patternRoutes[pattern] = append(patternRoutes[pattern], route)
sortedPattern = append(sortedPattern, pattern)
// 预编译正则并缓存 (优化点: 避免每次请求重新编译)
compilePattern(pattern)
} else {
r.methodRoutes[method][path] = route
r.methodRoutes[http.MethodOptions][path] = route // 默认 options 方法
}
}
// compilePattern 编译并缓存正则.
func compilePattern(pattern string) *regexp.Regexp {
patternRegexpMu.RLock()
if re, ok := patternRegexpCache[pattern]; ok {
patternRegexpMu.RUnlock()
return re
}
patternRegexpMu.RUnlock()
patternRegexpMu.Lock()
defer patternRegexpMu.Unlock()
if re, ok := patternRegexpCache[pattern]; ok {
return re
}
re := regexp.MustCompile(pattern)
patternRegexpCache[pattern] = re
return re
}
func (r *Router) getPattern(str string, any bool) (paramName, pattern string) {
params := patternRouteCompiler.FindAllStringSubmatch(str, 1)
if len(params[0][2]) == 0 {
if any {
params[0][2] = patternMap[":any"]
} else {
params[0][2] = patternMap[":string"]
}
}
pattern = strings.Trim(strings.Trim(params[0][2], "<"), ">")
if len(pattern) > 0 {
pattern = fmt.Sprintf("(%s)", pattern)
}
paramName = params[0][1]
return
}
// matchRoute 匹配路由.
func (r *Router) matchRoute(ctx *Context) *RouteEntry {
method, fullPath := ctx.Method(), strings.TrimRight(ctx.Path(), urlSeparator)
if len(fullPath) == 0 {
fullPath = urlSeparator
}
if route, ok := r.methodRoutes[method][fullPath]; ok {
return route
}
pathInfo := strings.Split(fullPath, urlSeparator)
l := len(pathInfo)
for i := 1; i <= l; i++ {
p := strings.Join(pathInfo[:i], urlSeparator)
groupRouter, ok := r.groups[p]
if ok {
if route := groupRouter.lookupGroupRoute(i, method, pathInfo, fullPath); route != nil {
return route
}
}
}
// 使用缓存的正则进行匹配 (优化点: FindStringSubmatch 单次匹配, 避免全量遍历)
for _, pattern := range sortedPattern {
routes := patternRoutes[pattern]
reg := compilePattern(pattern)
matched := reg.FindStringSubmatch(ctx.Path())
if len(matched) == 0 {
continue
}
matchedValues := matched[1:]
for _, route := range routes {
if route.Method != method {
continue
}
for idx, paramKey := range route.Param {
ctx.Params().Set(paramKey, matchedValues[idx])
}
return route
}
}
return nil
}
func (r *Router) lookupGroupRoute(i int, method string, pathInfo []string, fullPath string) *RouteEntry {
p := urlSeparator + strings.Join(pathInfo[i:], urlSeparator)
for routePath, route := range r.methodRoutes[method] {
if routePath != p || route.Method != method {
continue
}
return route
}
if r.groups != nil {
for _, v := range r.groups {
if i+1 < len(pathInfo) && strings.Contains(fullPath, v.prefix) {
if route := v.lookupGroupRoute(i+1, method, pathInfo, fullPath); route != nil {
return route
}
}
}
}
return nil
}
// Group 创建路由分组.
func (r *Router) Group(prefix string, middleWares ...Handler) *Router {
prefix = fmt.Sprintf("%s%s", r.prefix, prefix)
g := &Router{
prefix: prefix,
groups: map[string]*Router{},
middleWares: r.middleWares[:],
}
g.methodRoutes = initRouteEntity()
g.middleWares = append(g.middleWares, middleWares...)
r.groups[prefix] = g
return g
}
// Use 注册中间件.
func (r *Router) Use(middleWares ...Handler) {
r.middleWares = append(r.middleWares, middleWares...)
}
// Favicon 注册 favicon 路由.
func (r *Router) Favicon(file any) {
r.GET("/favicon.ico", func(c *Context) {
if filename, ok := file.(string); ok {
if mimeType := gomime.TypeByExtension(filepath.Ext(filename)); len(mimeType) > 0 {
c.Response.Header().Set(HeaderContentType, mimeType)
}
c.Response.SendFile(filename, c.Request)
} else if file, ok := file.(fs.File); ok {
defer file.Close()
info, _ := file.Stat()
if mimeType := gomime.TypeByExtension(filepath.Ext(info.Name())); len(mimeType) > 0 {
c.Response.Header().Set(HeaderContentType, mimeType)
}
if err := c.Response.ReadAll(file, -1); err != nil {
c.Abort(http.StatusInternalServerError, err.Error())
}
} else {
panic(errors.New("unsupported type"))
}
})
}
// StaticFS 注册基于 fs.FS 的静态文件服务.
// 使用流式传输, 避免大文件全量读取导致 OOM.
func (r *Router) StaticFS(urlPath string, f fs.FS, filePrefix string, indexfile ...string) {
handler := func(c *Context) {
filename := c.Params().Get(FilePathParam)
if len(filename) == 0 {
if len(indexfile) == 0 {
c.Abort(http.StatusNotFound)
return
}
filename = indexfile[0]
}
file, err := f.Open(strings.Replace(filepath.Join(filePrefix, filename), "\\", urlSeparator, -1))
if err != nil {
if os.IsNotExist(err) {
c.Abort(http.StatusNotFound)
} else {
c.Abort(http.StatusInternalServerError, err.Error())
}
return
}
defer file.Close()
mimeType := gomime.TypeByExtension(filepath.Ext(filename))
if len(mimeType) > 0 {
c.Response.Header().Set(HeaderContentType, mimeType)
}
// 流式传输: 标记 streamed, 直接写入底层 ResponseWriter
w := c.Response.StreamFile()
if _, err := io.Copy(w, file); err != nil {
c.Logger().Warn("static fs copy: " + err.Error())
}
}
routePath := path.Join(urlPath, "*"+FilePathParam)
r.GET(routePath, handler)
r.HEAD(routePath, handler)
}
// Static 注册基于目录的静态文件服务, 平替 fasthttp.FSHandler.
// 使用 http.FileServer + http.StripPrefix, 在注册时创建一次, 避免每次请求重建.
func (r *Router) Static(urlPath, dir string) {
// 注册时创建一次 FileServer, 避免每次请求重建
fileServer := http.StripPrefix(urlPath, http.FileServer(http.Dir(dir)))
handler := func(c *Context) {
fName := c.Params().Get(FilePathParam)
if len(fName) == 0 {
fName = "index.html"
}
// 重写请求路径以匹配 strip prefix.
// 使用 WithContext 浅拷贝 Request, 仅替换 URL, 避免深拷贝 header map 的开销.
req := c.Request.WithContext(c.Request.Context())
req.URL = &url.URL{Path: "/" + fName, RawQuery: c.Request.URL.RawQuery}
// 标记流式响应, 跳过缓冲
w := c.Response.StreamFile()
fileServer.ServeHTTP(w, req)
}
routePath := path.Join(urlPath, "*"+FilePathParam)
r.GET(routePath, handler)
r.HEAD(routePath, handler)
}
// StaticFile 注册单文件服务.
func (r *Router) StaticFile(path, file string, mws ...Handler) {
r.GET(path, func(c *Context) {
w := c.Response.StreamFile()
http.ServeFile(w, c.Request, file)
}, mws...)
}
// GET 注册 GET 路由.
func (r *Router) GET(path string, handle Handler, mws ...Handler) {
r.AddRoute(http.MethodGet, path, handle, mws...)
}
// PUT 注册 PUT 路由.
func (r *Router) PUT(path string, handle Handler, mws ...Handler) {
r.AddRoute(http.MethodPut, path, handle, mws...)
}
// ANY 注册所有方法路由.
func (r *Router) ANY(path string, handle Handler, mws ...Handler) {
r.GET(path, handle, mws...)
r.PUT(path, handle, mws...)
r.HEAD(path, handle, mws...)
r.POST(path, handle, mws...)
r.DELETE(path, handle, mws...)
}
// POST 注册 POST 路由.
func (r *Router) POST(path string, handle Handler, mws ...Handler) {
r.AddRoute(http.MethodPost, path, handle, mws...)
}
// HEAD 注册 HEAD 路由.
func (r *Router) HEAD(path string, handle Handler, mws ...Handler) {
r.AddRoute(http.MethodHead, path, handle, mws...)
}
// DELETE 注册 DELETE 路由.
func (r *Router) DELETE(path string, handle Handler, mws ...Handler) {
r.AddRoute(http.MethodDelete, path, handle, mws...)
}
// initRouteEntity 初始化路由 map.
func initRouteEntity() routerMap {
return routerMap{
http.MethodGet: {},
http.MethodPost: {},
http.MethodPut: {},
http.MethodHead: {},
http.MethodDelete: {},
http.MethodOptions: {},
http.MethodPatch: {}}
}
// upperCharRegexp 预编译正则, 避免每次调用 upperCharToUnderLine 时重新编译.
var upperCharRegexp = regexp.MustCompile("([A-Z])")
// upperCharToUnderLine 大写字符转下划线.
func upperCharToUnderLine(path string) string {
return strings.TrimLeft(upperCharRegexp.ReplaceAllStringFunc(path, func(s string) string {
return strings.ToLower("_" + s)
}), "_")
}
// RegisterOnInterrupt 注册中断时回调.
func RegisterOnInterrupt(handler func()) {
shutdownBeforeHandler = append(shutdownBeforeHandler, handler)
}
// SetControllerDefaultAction 设置控制器默认方法.
func SetControllerDefaultAction(str string) {
controllerDefaultAction = str
}