-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathelton.go
More file actions
851 lines (763 loc) · 23.2 KB
/
Copy pathelton.go
File metadata and controls
851 lines (763 loc) · 23.2 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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
// MIT License
// Copyright (c) 2020 Tree Xie
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package elton
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"reflect"
"runtime"
"slices"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/vicanso/hes"
"github.com/vicanso/keygrip"
)
// Status is the running status of elton
type Status int32
const (
// StatusRunning running status
StatusRunning Status = iota
// StatusClosing closing status
StatusClosing
// StatusClosed closed status
StatusClosed
)
// ErrServerNotInitialized the http server of elton is not initialized
var ErrServerNotInitialized = errors.New("server is not initialized")
type (
// Skipper check for skip middleware
Skipper func(c *Context) bool
// RouterInfo router's info
RouterInfo struct {
Method string `json:"method,omitempty"`
Route string `json:"route,omitempty"`
}
// Elton web framework instance
Elton struct {
// Server http server
Server *http.Server
// ErrorHandler set the function for error handler
ErrorHandler ErrorHandler
// NotFoundHandler set the function for not found handler
NotFoundHandler http.HandlerFunc
// MethodNotAllowedHandler set the function for method not allowed handler
MethodNotAllowedHandler http.HandlerFunc
// GenerateID generate id function, will use it to create context's id
GenerateID GenerateID
// EnableTrace enable trace
EnableTrace bool
// SignedKeys signed keys
SignedKeys SignedKeysGenerator
// status of elton
status atomic.Int32
// mux is the standard library router (Go 1.22+ patterns / wildcards)
mux *http.ServeMux
// routers all router infos
routers []RouterInfo
// middlewares middleware function
middlewares []Handler
// preMiddlewares pre middleware function
preMiddlewares []PreHandler
errorListeners []ErrorListener
traceListeners []TraceListener
// doneListeners request done
doneListeners []DoneListener
// beforeListeners before request handle
beforeListeners []BeforeListener
// functionInfos the function address:name map
functionInfos map[uintptr]string
// functionInfosMutex protects functionInfos for concurrent access
functionInfosMutex sync.RWMutex
// keygrip 缓存:避免每次 SignedCookie 都 keygrip.New
kgMu sync.Mutex
kgKeys []string
kg *keygrip.Keygrip
ctxPool sync.Pool
}
// Router router
Router struct {
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
HandleList []Handler `json:"-"`
}
// Group group router
Group struct {
Path string
HandlerList []Handler
routers []*Router
children []*Group
}
// ErrorHandler error handle function
ErrorHandler func(*Context, error)
// GenerateID generate context id
GenerateID func() string
// Handler elton handle function
Handler func(*Context) error
// ErrorListener error listener function
ErrorListener func(*Context, error)
// TraceListener trace listener
TraceListener func(*Context, TraceInfos)
// DoneListener request done listener
DoneListener func(*Context)
// BeforeListener before request handle listener
BeforeListener func(*Context)
// PreHandler pre handler
PreHandler func(*http.Request)
)
var _ http.Handler = (*Elton)(nil)
var _ context.Context = (*Context)(nil)
// DefaultSkipper default skipper function
func DefaultSkipper(c *Context) bool {
return c.Committed
}
// New returns a new elton instance
func New() *Elton {
e := NewWithoutServer()
s := &http.Server{
Handler: e,
}
e.Server = s
return e
}
// NewWithoutServer returns a new elton instance without http server
func NewWithoutServer() *Elton {
e := &Elton{
mux: http.NewServeMux(),
functionInfos: make(map[uintptr]string),
}
e.ctxPool.New = func() any {
c := &Context{
elton: e,
Params: new(RouteParams),
handlerIndex: -1,
}
c.initBoundNext()
return c
}
return e
}
// NewGroup returns a new router group
func NewGroup(path string, handlerList ...Handler) *Group {
return &Group{
Path: path,
HandlerList: handlerList,
}
}
// IsIntranet reports whether s is a loopback, private, or link-local address.
// Invalid or empty values return false.
func IsIntranet(s string) bool {
ip := net.ParseIP(s)
if ip == nil {
return false
}
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
}
// SetFunctionName sets the name of handler function,
// it will use to http timing
func (e *Elton) SetFunctionName(fn any, name string) {
p := reflect.ValueOf(fn).Pointer()
e.functionInfosMutex.Lock()
e.functionInfos[p] = name
e.functionInfosMutex.Unlock()
}
// GetFunctionName return the name of handler function
func (e *Elton) GetFunctionName(fn any) string {
p := reflect.ValueOf(fn).Pointer()
e.functionInfosMutex.RLock()
name := e.functionInfos[p]
e.functionInfosMutex.RUnlock()
if name != "" {
return name
}
return runtime.FuncForPC(p).Name()
}
// ensureFunctionName returns the handler name, caching runtime name if unset.
func (e *Elton) ensureFunctionName(fn any) string {
p := reflect.ValueOf(fn).Pointer()
e.functionInfosMutex.RLock()
name := e.functionInfos[p]
e.functionInfosMutex.RUnlock()
if name != "" {
return name
}
name = runtime.FuncForPC(p).Name()
e.functionInfosMutex.Lock()
// double-check:并发 ensure 时只写一次
if existing := e.functionInfos[p]; existing != "" {
name = existing
} else {
e.functionInfos[p] = name
}
e.functionInfosMutex.Unlock()
return name
}
// functionNameLocked resolves name; caller must hold functionInfosMutex (RLock).
func (e *Elton) functionNameLocked(fn Handler) string {
p := reflect.ValueOf(fn).Pointer()
if name := e.functionInfos[p]; name != "" {
return name
}
return runtime.FuncForPC(p).Name()
}
// keygrip returns a cached keygrip for SignedKeys, rebuilding when keys change.
func (e *Elton) keygrip() *keygrip.Keygrip {
if e.SignedKeys == nil {
return nil
}
keys := e.SignedKeys.Keys()
if len(keys) == 0 {
return nil
}
e.kgMu.Lock()
defer e.kgMu.Unlock()
if e.kg != nil && slices.Equal(e.kgKeys, keys) {
return e.kg
}
e.kgKeys = slices.Clone(keys)
e.kg = keygrip.New(keys)
return e.kg
}
// ListenAndServe listens the addr and serve http,
// it returns ErrServerNotInitialized if the server of elton is nil.
func (e *Elton) ListenAndServe(addr string) error {
if e.Server == nil {
return ErrServerNotInitialized
}
e.Server.Addr = addr
return e.Server.ListenAndServe()
}
// ListenAndServeTLS listens the addr and serve https,
// it returns ErrServerNotInitialized if the server of elton is nil.
func (e *Elton) ListenAndServeTLS(addr, certFile, keyFile string) error {
if e.Server == nil {
return ErrServerNotInitialized
}
e.Server.Addr = addr
return e.Server.ListenAndServeTLS(certFile, keyFile)
}
// Serve serves http server,
// it returns ErrServerNotInitialized if the server of elton is nil.
func (e *Elton) Serve(l net.Listener) error {
if e.Server == nil {
return ErrServerNotInitialized
}
return e.Server.Serve(l)
}
// Close closes the http server
func (e *Elton) Close() error {
if e.Server == nil {
return ErrServerNotInitialized
}
return e.Server.Close()
}
// Shutdown gracefully shuts down the http server without
// interrupting any active connections
func (e *Elton) Shutdown(ctx context.Context) error {
if e.Server == nil {
return ErrServerNotInitialized
}
return e.Server.Shutdown(ctx)
}
// GracefulClose closes the http server gracefully.
// It sets the status to be closing (rejecting new requests with 503),
// waits for the delay, then shuts down the server.
// ctx取消时停止等待并立即进入shutdown(此时Shutdown会关闭监听
// 并立即返回ctx.Err,不再等待活跃连接处理完成)。
func (e *Elton) GracefulClose(ctx context.Context, delay time.Duration) error {
e.status.Store(int32(StatusClosing))
if delay > 0 {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
}
e.status.Store(int32(StatusClosed))
return e.Shutdown(ctx)
}
// Status returns status of elton
func (e *Elton) Status() Status {
return Status(e.status.Load())
}
// Closing judge the status whether is closing
func (e *Elton) Closing() bool {
return e.Status() == StatusClosing
}
// Running judge the status whether is running
func (e *Elton) Running() bool {
return e.Status() == StatusRunning
}
// ServeHTTP http handler
func (e *Elton) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
status := e.Status()
// 非运行中的状态
if status != StatusRunning {
resp.WriteHeader(http.StatusServiceUnavailable)
_, err := fmt.Fprintf(resp, "service is not available, status is %d", status)
if err != nil {
e.emitError(resp, req, err)
}
return
}
for _, preHandler := range e.preMiddlewares {
preHandler(req)
}
// Single ServeMux match: PathValue is filled here. edgeWriter lets elton routes
// mark themselves handled; mux-internal 404/405 are replaced by elton handlers,
// while redirects (and other non-route mux responses) are flushed as-is.
// edgeWriter is pooled; handlers must detach it from Context before return
// (see detachEdgeFromContext in the route HandleFunc).
ew := acquireEdgeWriter(resp)
e.mux.ServeHTTP(ew, req)
if !ew.handled {
switch ew.status {
case http.StatusMethodNotAllowed:
if allow := ew.Header().Get("Allow"); allow != "" {
resp.Header().Set("Allow", allow)
}
e.methodNotAllowed(resp, req)
case http.StatusNotFound, 0:
e.notFound(resp, req)
default:
// trailing-slash redirect, sanitizing redirect, etc.
ew.flush()
}
}
releaseEdgeWriter(ew)
}
// Routers returns routers of elton
func (e *Elton) Routers() []RouterInfo {
return slices.Clone(e.routers)
}
// Handle adds http handle function.
// 注册时将当时的全局中间件(Use)与该路由 handler 快照合并为一条固定执行链;
// 请求到达时通过 c.Next() 推进(洋葱模型),Next 使用 Context 上复用的 boundNext,
// 避免每请求分配闭包:
// - 任一环节返回 error 则中断,触发 error 监听器并输出错误响应;
// - c.Committed 为 true 时 Next 短路,不再执行后续 handler;
// - 链执行完成后,统一将 BodyBuffer(或 reader 类型的 Body)写出至响应。
//
// path 使用 net/http ServeMux 模式(Go 1.22+):{name}、{name...}、{$};
// 仍兼容段首 :name 与末尾 /*(分别转为 {name}、{path...})。
// 注册 pattern 为 "METHOD path";冲突的 pattern 会 panic(标准库行为)。
//
// 注意:应在 Listen 前完成 Use + 路由注册。某路由注册之后再 Use 的中间件
// 不会作用于该路由(链在 Handle 时已快照)。
func (e *Elton) Handle(method, path string, handlerList ...Handler) *Elton {
for _, fn := range handlerList {
e.ensureFunctionName(fn)
}
path = normalizeRoutePath(path)
paramNames := extractParamNames(path)
// Snapshot: later e.Use does not change already-registered routes.
handlers := make([]Handler, 0, len(e.middlewares)+len(handlerList))
handlers = append(handlers, e.middlewares...)
handlers = append(handlers, handlerList...)
e.routers = append(e.routers, RouterInfo{
Method: method,
Route: path,
})
pattern := path
if method != "" {
pattern = method + " " + path
}
e.mux.HandleFunc(pattern, func(resp http.ResponseWriter, req *http.Request) {
// Mark before any write so application 404/405 is not treated as mux miss.
markRouteHandled(resp)
c := e.ctxPool.Get().(*Context)
c.Reset()
c.Request = req
c.Response = resp
c.handlers = handlers
c.handlerIndex = -1
// Detach edgeWriter before this func returns so ServeHTTP can pool it safely.
// Also returns Context to the pool when reuse is allowed.
defer func() {
detachEdgeFromContext(c)
if c.isReuse() {
e.ctxPool.Put(c)
}
}()
if e.GenerateID != nil {
c.ID = e.GenerateID()
}
// Fill Params in one pass with pre-sized slices (ToMap / Values[0] / tests).
if n := len(paramNames); n > 0 {
p := c.Params
if cap(p.Keys) < n {
p.Keys = make([]string, n)
p.Values = make([]string, n)
} else {
p.Keys = p.Keys[:n]
p.Values = p.Values[:n]
}
for i, name := range paramNames {
p.Keys[i] = name
p.Values[i] = req.PathValue(name)
}
}
if e.beforeListeners != nil {
e.emitBefore(c)
}
if e.doneListeners != nil {
defer e.emitDone(c)
}
c.Route = path
if e.EnableTrace {
maxNext := len(handlers)
trace := &Trace{
Infos: make(TraceInfos, 0, maxNext),
}
c.activeTrace = trace
c.WithContext(context.WithValue(c.Context(), ContextTraceKey, trace))
if cap(c.handlerNames) < maxNext {
c.handlerNames = make([]string, maxNext)
} else {
c.handlerNames = c.handlerNames[:maxNext]
}
e.functionInfosMutex.RLock()
for i := range maxNext {
c.handlerNames[i] = e.functionNameLocked(handlers[i])
}
e.functionInfosMutex.RUnlock()
}
err := c.Next()
if c.activeTrace != nil {
c.activeTrace.Calculate()
e.EmitTrace(c, c.activeTrace.Infos)
}
if err != nil {
e.EmitError(c, err)
}
// 如果已commit 表示返回数据已设置,无需处理
if c.Committed {
return
}
c.Committed = true
// 如果出错则触发出错处理,返回
if err != nil {
// 出错时reader body不会被输出,关闭避免资源泄漏
c.closeReaderBody()
e.error(c, err)
return
}
// 需要在设置status code之前设置响应长度
if c.BodyBuffer != nil {
// BodyBuffer优先输出,若Body为未使用的reader则关闭
c.closeReaderBody()
c.SetHeader(HeaderContentLength, strconv.Itoa(c.BodyBuffer.Len()))
}
if c.StatusCode != 0 {
c.Response.WriteHeader(c.StatusCode)
}
if c.BodyBuffer != nil {
_, responseErr := c.Response.Write(c.BodyBuffer.Bytes())
if responseErr != nil {
e.EmitError(c, responseErr)
}
} else if c.IsReaderBody() {
r, _ := c.Body.(io.Reader)
_, pipeErr := c.Pipe(r)
if pipeErr != nil {
e.EmitError(c, pipeErr)
}
}
})
return e
}
// GET adds http get method handle
func (e *Elton) GET(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodGet, path, handlerList...)
}
// POST adds http post method handle
func (e *Elton) POST(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodPost, path, handlerList...)
}
// PUT adds http put method handle
func (e *Elton) PUT(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodPut, path, handlerList...)
}
// PATCH adds http patch method handle
func (e *Elton) PATCH(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodPatch, path, handlerList...)
}
// DELETE adds http delete method handle
func (e *Elton) DELETE(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodDelete, path, handlerList...)
}
// HEAD adds http head method handle
func (e *Elton) HEAD(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodHead, path, handlerList...)
}
// OPTIONS adds http options method handle
func (e *Elton) OPTIONS(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodOptions, path, handlerList...)
}
// TRACE adds http trace method handle
func (e *Elton) TRACE(path string, handlerList ...Handler) *Elton {
return e.Handle(http.MethodTrace, path, handlerList...)
}
// ALL adds http all method handle
func (e *Elton) ALL(path string, handlerList ...Handler) *Elton {
return e.Multi(methods, path, handlerList...)
}
// Multi adds multi method
func (e *Elton) Multi(methods []string, path string, handlerList ...Handler) *Elton {
for _, method := range methods {
e.Handle(method, path, handlerList...)
}
return e
}
// Use adds middleware handler function to elton's middleware list
func (e *Elton) Use(handlerList ...Handler) *Elton {
for _, fn := range handlerList {
e.ensureFunctionName(fn)
}
e.middlewares = append(e.middlewares, handlerList...)
return e
}
// UseWithName adds middleware and set handler function's name
func (e *Elton) UseWithName(handler Handler, name string) *Elton {
e.SetFunctionName(handler, name)
return e.Use(handler)
}
// Pre adds pre middleware function handler to elton's pre middleware list
func (e *Elton) Pre(handlerList ...PreHandler) *Elton {
e.preMiddlewares = append(e.preMiddlewares, handlerList...)
return e
}
// notFound not found handle
func (e *Elton) notFound(resp http.ResponseWriter, req *http.Request) *Elton {
if e.NotFoundHandler != nil {
e.NotFoundHandler(resp, req)
return e
}
resp.WriteHeader(http.StatusNotFound)
_, err := resp.Write([]byte("Not Found"))
if err != nil {
e.emitError(resp, req, err)
}
return e
}
// methodNotAllowed method not allowed handle
func (e *Elton) methodNotAllowed(resp http.ResponseWriter, req *http.Request) *Elton {
if e.MethodNotAllowedHandler != nil {
e.MethodNotAllowedHandler(resp, req)
return e
}
resp.WriteHeader(http.StatusMethodNotAllowed)
_, err := resp.Write([]byte("Method Not Allowed"))
if err != nil {
e.emitError(resp, req, err)
}
return e
}
// error error handle
func (e *Elton) error(c *Context, err error) *Elton {
// 出错时清除部分响应头
for _, key := range []string{
HeaderETag,
HeaderLastModified,
HeaderContentEncoding,
HeaderContentLength,
} {
c.SetHeader(key, "")
}
if e.ErrorHandler != nil {
e.ErrorHandler(c, err)
return e
}
resp := c.Response
status := http.StatusInternalServerError
message := err.Error()
he := &hes.Error{}
if errors.As(err, &he) {
status = he.StatusCode
message = he.Error()
}
resp.WriteHeader(status)
_, err = resp.Write([]byte(message))
if err != nil {
e.EmitError(c, err)
}
return e
}
// EmitError emits an error event, it will call the listen functions of error event
func (e *Elton) EmitError(c *Context, err error) *Elton {
lns := e.errorListeners
for _, ln := range lns {
ln(c, err)
}
return e
}
func (e *Elton) emitError(resp http.ResponseWriter, req *http.Request, err error) {
e.EmitError(&Context{
Request: req,
Response: resp,
elton: e,
}, err)
}
// OnError adds listen to error event
func (e *Elton) OnError(ln ErrorListener) *Elton {
e.errorListeners = append(e.errorListeners, ln)
return e
}
// EmitTrace emits a trace event, it will call the listen functions of trace event
func (e *Elton) EmitTrace(c *Context, infos TraceInfos) *Elton {
lns := e.traceListeners
for _, ln := range lns {
ln(c, infos)
}
return e
}
// OnTrace adds listen to trace event
func (e *Elton) OnTrace(ln TraceListener) *Elton {
e.traceListeners = append(e.traceListeners, ln)
return e
}
// OnDone adds listen to request done, it will be triggered
// when the request handle is done
func (e *Elton) OnDone(ln DoneListener) *Elton {
e.doneListeners = append(e.doneListeners, ln)
return e
}
func (e *Elton) emitDone(c *Context) {
for _, ln := range e.doneListeners {
ln(c)
}
}
// OnBefore adds listen to before request done(after pre middlewares, before middlewares)
func (e *Elton) OnBefore(ln BeforeListener) *Elton {
e.beforeListeners = append(e.beforeListeners, ln)
return e
}
func (e *Elton) emitBefore(c *Context) {
for _, ln := range e.beforeListeners {
ln(c)
}
}
// AddGroup adds the group and its sub groups to elton
func (e *Elton) AddGroup(groups ...*Group) *Elton {
for _, g := range groups {
for _, r := range g.routers {
e.Handle(r.Method, r.Path, r.HandleList...)
}
e.AddGroup(g.children...)
}
return e
}
func (g *Group) merge(s2 []Handler) []Handler {
s1 := g.HandlerList
fns := make([]Handler, len(s1)+len(s2))
copy(fns, s1)
copy(fns[len(s1):], s2)
return fns
}
// NewGroup returns a new sub group of the group,
// the path and handler list will be merged with the parent's.
// The sub group will be added to elton together with its parent
// by elton.AddGroup.
func (g *Group) NewGroup(path string, handlerList ...Handler) *Group {
child := &Group{
Path: g.Path + path,
HandlerList: g.merge(handlerList),
}
g.children = append(g.children, child)
return child
}
func (g *Group) handle(method, path string, handlerList ...Handler) *Group {
g.routers = append(g.routers, &Router{
Method: method,
Path: g.Path + path,
HandleList: g.merge(handlerList),
})
return g
}
// GET adds http get method handler to group
func (g *Group) GET(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodGet, path, handlerList...)
}
// POST adds http post method handler to group
func (g *Group) POST(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodPost, path, handlerList...)
}
// PUT adds http put method handler to group
func (g *Group) PUT(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodPut, path, handlerList...)
}
// PATCH adds http patch method handler to group
func (g *Group) PATCH(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodPatch, path, handlerList...)
}
// DELETE adds http delete method handler to group
func (g *Group) DELETE(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodDelete, path, handlerList...)
}
// HEAD adds http head method handler to group
func (g *Group) HEAD(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodHead, path, handlerList...)
}
// OPTIONS adds http options method handler to group
func (g *Group) OPTIONS(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodOptions, path, handlerList...)
}
// TRACE adds http trace method handler to group
func (g *Group) TRACE(path string, handlerList ...Handler) *Group {
return g.handle(http.MethodTrace, path, handlerList...)
}
// ALL adds http all methods handler to group
func (g *Group) ALL(path string, handlerList ...Handler) *Group {
return g.Multi(methods, path, handlerList...)
}
// Multi adds multi http methods handler to group
func (g *Group) Multi(methods []string, path string, handlerList ...Handler) *Group {
for _, method := range methods {
g.handle(method, path, handlerList...)
}
return g
}
// Compose composes handler list as a handler
func Compose(handlerList ...Handler) Handler {
max := len(handlerList)
if max == 0 {
panic(errors.New("handler function is required"))
}
return func(c *Context) (err error) {
// 保存原有的next函数
originalNext := c.Next
index := -1
// 新创建一个next的调用链
c.Next = func() error {
index++
// 如果已执行成所有的next,则转回原有的调用链
if index >= max {
c.Next = originalNext
return c.Next()
}
return handlerList[index](c)
}
return c.Next()
}
}