forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
1595 lines (1385 loc) · 44.1 KB
/
http.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
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package iris
import (
"bytes"
"crypto/tls"
"net"
"net/http"
"net/http/pprof"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/iris-contrib/errors"
"github.com/iris-contrib/letsencrypt"
"github.com/iris-contrib/logger"
"github.com/kataras/iris/config"
"github.com/kataras/iris/utils"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
const (
// MethodGet "GET"
MethodGet = "GET"
// MethodPost "POST"
MethodPost = "POST"
// MethodPut "PUT"
MethodPut = "PUT"
// MethodDelete "DELETE"
MethodDelete = "DELETE"
// MethodConnect "CONNECT"
MethodConnect = "CONNECT"
// MethodHead "HEAD"
MethodHead = "HEAD"
// MethodPatch "PATCH"
MethodPatch = "PATCH"
// MethodOptions "OPTIONS"
MethodOptions = "OPTIONS"
// MethodTrace "TRACE"
MethodTrace = "TRACE"
)
var (
// AllMethods "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE"
AllMethods = [...]string{MethodGet, MethodPost, MethodPut, MethodDelete, MethodConnect, MethodHead, MethodPatch, MethodOptions, MethodTrace}
/* methods as []byte, these are really used by iris */
// methodGetBytes "GET"
methodGetBytes = []byte(MethodGet)
// methodPostBytes "POST"
methodPostBytes = []byte(MethodPost)
// methodPutBytes "PUT"
methodPutBytes = []byte(MethodPut)
// methodDeleteBytes "DELETE"
methodDeleteBytes = []byte(MethodDelete)
// methodConnectBytes "CONNECT"
methodConnectBytes = []byte(MethodConnect)
// methodHeadBytes "HEAD"
methodHeadBytes = []byte(MethodHead)
// methodPatchBytes "PATCH"
methodPatchBytes = []byte(MethodPatch)
// methodOptionsBytes "OPTIONS"
methodOptionsBytes = []byte(MethodOptions)
// methodTraceBytes "TRACE"
methodTraceBytes = []byte(MethodTrace)
/* */
)
const (
// StatusContinue http status '100'
StatusContinue = 100
// StatusSwitchingProtocols http status '101'
StatusSwitchingProtocols = 101
// StatusOK http status '200'
StatusOK = 200
// StatusCreated http status '201'
StatusCreated = 201
// StatusAccepted http status '202'
StatusAccepted = 202
// StatusNonAuthoritativeInfo http status '203'
StatusNonAuthoritativeInfo = 203
// StatusNoContent http status '204'
StatusNoContent = 204
// StatusResetContent http status '205'
StatusResetContent = 205
// StatusPartialContent http status '206'
StatusPartialContent = 206
// StatusMultipleChoices http status '300'
StatusMultipleChoices = 300
// StatusMovedPermanently http status '301'
StatusMovedPermanently = 301
// StatusFound http status '302'
StatusFound = 302
// StatusSeeOther http status '303'
StatusSeeOther = 303
// StatusNotModified http status '304'
StatusNotModified = 304
// StatusUseProxy http status '305'
StatusUseProxy = 305
// StatusTemporaryRedirect http status '307'
StatusTemporaryRedirect = 307
// StatusBadRequest http status '400'
StatusBadRequest = 400
// StatusUnauthorized http status '401'
StatusUnauthorized = 401
// StatusPaymentRequired http status '402'
StatusPaymentRequired = 402
// StatusForbidden http status '403'
StatusForbidden = 403
// StatusNotFound http status '404'
StatusNotFound = 404
// StatusMethodNotAllowed http status '405'
StatusMethodNotAllowed = 405
// StatusNotAcceptable http status '406'
StatusNotAcceptable = 406
// StatusProxyAuthRequired http status '407'
StatusProxyAuthRequired = 407
// StatusRequestTimeout http status '408'
StatusRequestTimeout = 408
// StatusConflict http status '409'
StatusConflict = 409
// StatusGone http status '410'
StatusGone = 410
// StatusLengthRequired http status '411'
StatusLengthRequired = 411
// StatusPreconditionFailed http status '412'
StatusPreconditionFailed = 412
// StatusRequestEntityTooLarge http status '413'
StatusRequestEntityTooLarge = 413
// StatusRequestURITooLong http status '414'
StatusRequestURITooLong = 414
// StatusUnsupportedMediaType http status '415'
StatusUnsupportedMediaType = 415
// StatusRequestedRangeNotSatisfiable http status '416'
StatusRequestedRangeNotSatisfiable = 416
// StatusExpectationFailed http status '417'
StatusExpectationFailed = 417
// StatusTeapot http status '418'
StatusTeapot = 418
// StatusPreconditionRequired http status '428'
StatusPreconditionRequired = 428
// StatusTooManyRequests http status '429'
StatusTooManyRequests = 429
// StatusRequestHeaderFieldsTooLarge http status '431'
StatusRequestHeaderFieldsTooLarge = 431
// StatusUnavailableForLegalReasons http status '451'
StatusUnavailableForLegalReasons = 451
// StatusInternalServerError http status '500'
StatusInternalServerError = 500
// StatusNotImplemented http status '501'
StatusNotImplemented = 501
// StatusBadGateway http status '502'
StatusBadGateway = 502
// StatusServiceUnavailable http status '503'
StatusServiceUnavailable = 503
// StatusGatewayTimeout http status '504'
StatusGatewayTimeout = 504
// StatusHTTPVersionNotSupported http status '505'
StatusHTTPVersionNotSupported = 505
// StatusNetworkAuthenticationRequired http status '511'
StatusNetworkAuthenticationRequired = 511
)
var statusText = map[int]string{
StatusContinue: "Continue",
StatusSwitchingProtocols: "Switching Protocols",
StatusOK: "OK",
StatusCreated: "Created",
StatusAccepted: "Accepted",
StatusNonAuthoritativeInfo: "Non-Authoritative Information",
StatusNoContent: "No Content",
StatusResetContent: "Reset Content",
StatusPartialContent: "Partial Content",
StatusMultipleChoices: "Multiple Choices",
StatusMovedPermanently: "Moved Permanently",
StatusFound: "Found",
StatusSeeOther: "See Other",
StatusNotModified: "Not Modified",
StatusUseProxy: "Use Proxy",
StatusTemporaryRedirect: "Temporary Redirect",
StatusBadRequest: "Bad Request",
StatusUnauthorized: "Unauthorized",
StatusPaymentRequired: "Payment Required",
StatusForbidden: "Forbidden",
StatusNotFound: "Not Found",
StatusMethodNotAllowed: "Method Not Allowed",
StatusNotAcceptable: "Not Acceptable",
StatusProxyAuthRequired: "Proxy Authentication Required",
StatusRequestTimeout: "Request Timeout",
StatusConflict: "Conflict",
StatusGone: "Gone",
StatusLengthRequired: "Length Required",
StatusPreconditionFailed: "Precondition Failed",
StatusRequestEntityTooLarge: "Request Entity Too Large",
StatusRequestURITooLong: "Request URI Too Long",
StatusUnsupportedMediaType: "Unsupported Media Type",
StatusRequestedRangeNotSatisfiable: "Requested Range Not Satisfiable",
StatusExpectationFailed: "Expectation Failed",
StatusTeapot: "I'm a teapot",
StatusPreconditionRequired: "Precondition Required",
StatusTooManyRequests: "Too Many Requests",
StatusRequestHeaderFieldsTooLarge: "Request Header Fields Too Large",
StatusUnavailableForLegalReasons: "Unavailable For Legal Reasons",
StatusInternalServerError: "Internal Server Error",
StatusNotImplemented: "Not Implemented",
StatusBadGateway: "Bad Gateway",
StatusServiceUnavailable: "Service Unavailable",
StatusGatewayTimeout: "Gateway Timeout",
StatusHTTPVersionNotSupported: "HTTP Version Not Supported",
StatusNetworkAuthenticationRequired: "Network Authentication Required",
}
// StatusText returns a text for the HTTP status code. It returns the empty
// string if the code is unknown.
func StatusText(code int) string {
return statusText[code]
}
// Errors introduced by server.
var (
errServerPortAlreadyUsed = errors.New("Server can't run, port is already used")
errServerAlreadyStarted = errors.New("Server is already started and listening")
errServerHandlerMissing = errors.New("Handler is missing from server, can't start without handler")
errServerIsClosed = errors.New("Can't close the server, propably is already closed or never started")
errServerRemoveUnix = errors.New("Unexpected error when trying to remove unix socket file. Addr: %s | Trace: %s")
errServerChmod = errors.New("Cannot chmod %#o for %q: %s")
)
type (
// Server the http server
Server struct {
*fasthttp.Server
listener net.Listener
Config config.Server
tls bool
mu sync.Mutex
}
// ServerList contains the servers connected to the Iris station
ServerList struct {
mux *serveMux
servers []*Server
}
)
// newServer returns a pointer to a Server object, and set it's options if any, nothing more
func newServer(cfg config.Server) *Server {
if cfg.Name == "" {
cfg.Name = config.DefaultServerName
}
s := &Server{Server: &fasthttp.Server{Name: cfg.Name}, Config: cfg}
return s
}
// IsListening returns true if server is listening/started, otherwise false
func (s *Server) IsListening() bool {
if s == nil {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
return s.listener != nil && s.listener.Addr().String() != ""
}
// IsOpened checks if handler is not nil and returns true if not, otherwise false
// this is used to see if a server has opened, use IsListening if you want to see if the server is actually ready to serve connections
func (s *Server) IsOpened() bool {
if s == nil {
return false
}
return s.Server != nil && s.Server.Handler != nil
}
// IsSecure returns true if server uses TLS, otherwise false
func (s *Server) IsSecure() bool {
return s.tls || s.Config.AutoTLS // for any case
}
// Listener returns the net.Listener which this server (is) listening to
func (s *Server) Listener() net.Listener {
return s.listener
}
// Host returns the registered host for the server
func (s *Server) Host() string {
if s.Config.VListeningAddr != "" {
return s.Config.VListeningAddr
}
return s.Config.ListeningAddr
}
// Port returns the port which server listening for
// if no port given with the ListeningAddr, it returns 80
func (s *Server) Port() int {
a := s.Host()
if portIdx := strings.IndexByte(a, ':'); portIdx != -1 {
p, err := strconv.Atoi(a[portIdx+1:])
if err != nil {
if s.Config.AutoTLS {
return 443
}
return 80
} else {
return p
}
}
if s.Config.AutoTLS {
return 443
}
return 80
}
// Scheme returns http:// or https:// if SSL is enabled
func (s *Server) Scheme() string {
scheme := "http://"
// we need to be able to take that before(for testing &debugging) and after server's listen
if s.IsSecure() || (s.Config.CertFile != "" && s.Config.KeyFile != "") || s.Config.AutoTLS {
scheme = "https://"
}
// but if virtual scheme is setted and it differs from the real scheme, return the vscheme
// the developer should set it correctly, http:// or https:// or anything at the future:P
vscheme := s.Config.VScheme
if len(vscheme) > 0 && vscheme != scheme {
return vscheme
}
return scheme
}
// FullHost returns the scheme+host
func (s *Server) FullHost() string {
return s.Scheme() + s.Host()
}
// Hostname returns the hostname part of the host (host expect port)
func (s *Server) Hostname() string {
a := s.Host()
idxPort := strings.IndexByte(a, ':')
if idxPort > 0 {
// port exists, (it always exists for Config.ListeningAddr
return a[0:idxPort] // except the port
} // but for Config.VListeningAddr the developer maybe doesn't uses the host:port format
// so, if no port found, then return the Host as it is, it should be something 'mydomain.com'
return a
}
func (s *Server) listen() error {
if s.IsListening() {
return errServerAlreadyStarted.Return()
}
listener, err := net.Listen("tcp4", s.Config.ListeningAddr)
if err != nil {
return err
}
go s.serve(listener) // we don't catch underline errors, we catched all already
return nil
}
func (s *Server) listenUNIX() error {
mode := s.Config.Mode
addr := s.Config.ListeningAddr
if errOs := os.Remove(addr); errOs != nil && !os.IsNotExist(errOs) {
return errServerRemoveUnix.Format(s.Config.ListeningAddr, errOs.Error())
}
listener, err := net.Listen("unix", addr)
if err != nil {
return errServerPortAlreadyUsed.Return()
}
if err = os.Chmod(addr, mode); err != nil {
return errServerChmod.Format(mode, addr, err.Error())
}
go s.serve(listener) // we don't catch underline errors, we catched all already
return nil
}
//Serve just serves a listener, it is a blocking action, plugin.PostListen is not fired here.
func (s *Server) serve(l net.Listener) error {
s.mu.Lock()
s.listener = l
s.mu.Unlock()
if s.Config.CertFile != "" && s.Config.KeyFile != "" {
s.tls = true
return s.Server.ServeTLS(s.listener, s.Config.CertFile, s.Config.KeyFile)
} else if s.Config.AutoTLS {
var m letsencrypt.Manager
if err := m.CacheFile("letsencrypt.cache"); err != nil {
return err
}
tlsConfig := &tls.Config{GetCertificate: m.GetCertificate}
ln := tls.NewListener(l, tlsConfig)
s.tls = true
s.mu.Lock()
s.listener = ln
s.mu.Unlock()
}
return s.Server.Serve(s.listener)
}
// Open opens/starts/runs/listens (to) the server, listen tls if Cert && Key is registed, listenUNIX if Mode is registed, otherwise listen
func (s *Server) Open(h fasthttp.RequestHandler) error {
if h == nil {
return errServerHandlerMissing.Return()
}
if s.IsListening() {
return errServerAlreadyStarted.Return()
}
s.Server.MaxRequestBodySize = s.Config.MaxRequestBodySize
s.Server.ReadBufferSize = s.Config.ReadBufferSize
s.Server.WriteBufferSize = s.Config.WriteBufferSize
s.Server.ReadTimeout = s.Config.ReadTimeout
s.Server.WriteTimeout = s.Config.WriteTimeout
if s.Config.RedirectTo != "" {
// override the handler and redirect all requests to this addr
s.Server.Handler = func(reqCtx *fasthttp.RequestCtx) {
path := string(reqCtx.Path())
redirectTo := s.Config.RedirectTo
if path != "/" {
redirectTo += "/" + path
}
reqCtx.Redirect(redirectTo, StatusMovedPermanently)
}
} else {
s.Server.Handler = h
}
if s.Config.Mode > 0 {
return s.listenUNIX()
}
s.Config.ListeningAddr = config.ServerParseAddr(s.Config.ListeningAddr)
if s.Config.Virtual {
return nil
}
return s.listen()
}
// Close terminates the server
func (s *Server) Close() (err error) {
if !s.IsListening() {
return errServerIsClosed.Return()
}
err = s.listener.Close()
return
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// --------------------------------ServerList implementation-----------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// Add adds a server to the list by its config
// returns the new server
func (s *ServerList) Add(cfg config.Server) *Server {
srv := newServer(cfg)
s.servers = append(s.servers, srv)
return srv
}
// Len returns the size of the server list
func (s *ServerList) Len() int {
return len(s.servers)
}
// Main returns the main server,
// the last added server is the main server, even if's Virtual
func (s *ServerList) Main() (srv *Server) {
l := len(s.servers) - 1
for i := range s.servers {
if i == l {
return s.servers[i]
}
}
return nil
}
// Get returns the server by it's registered Address
func (s *ServerList) Get(addr string) (srv *Server) {
for i := range s.servers {
srv = s.servers[i]
if srv.Config.ListeningAddr == addr {
return
}
}
return
}
// GetAll returns all registered servers
func (s *ServerList) GetAll() []*Server {
return s.servers
}
// GetByIndex returns a server from the list by it's index
func (s *ServerList) GetByIndex(i int) *Server {
if len(s.servers) >= i+1 {
return s.servers[i]
}
return nil
}
// Remove deletes a server by it's registered Address
// returns true if something was removed, otherwise returns false
func (s *ServerList) Remove(addr string) bool {
servers := s.servers
for i := range servers {
srv := servers[i]
if srv.Config.ListeningAddr == addr {
copy(servers[i:], servers[i+1:])
servers[len(servers)-1] = nil
s.servers = servers[:len(servers)-1]
return true
}
}
return false
}
// CloseAll terminates all listening servers
// returns the first error, if erro happens it continues to closes the rest of the servers
func (s *ServerList) CloseAll() (err error) {
for i := range s.servers {
if err == nil {
err = s.servers[i].Close()
}
}
return
}
// OpenAll starts all servers
// returns the first error happens to one of these servers
// if one server gets error it closes the previous servers and exits from this process
func (s *ServerList) OpenAll() error {
l := len(s.servers) - 1
h := s.mux.ServeRequest()
for i := range s.servers {
if err := s.servers[i].Open(h); err != nil {
time.Sleep(2 * time.Second)
// for any case,
// we don't care about performance on initialization,
// we must make sure that the previous servers are running before closing them
s.CloseAll()
return err
}
if i == l {
s.mux.setHostname(s.servers[i].Hostname())
}
}
return nil
}
// GetAllOpened returns all opened/started servers
func (s *ServerList) GetAllOpened() (servers []*Server) {
for i := range s.servers {
if s.servers[i].IsOpened() {
servers = append(servers, s.servers[i])
}
}
return
}
// errHandler returns na error with message: 'Passed argument is not func(*Context) neither an object which implements the iris.Handler with Serve(ctx *Context)
// It seems to be a +type Points to: +pointer.'
var errHandler = errors.New("Passed argument is not func(*Context) neither an object which implements the iris.Handler with Serve(ctx *Context)\n It seems to be a %T Points to: %v.")
type (
// Handler the main Iris Handler interface.
Handler interface {
Serve(ctx *Context)
}
// HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
HandlerFunc func(*Context)
// Middleware is just a slice of Handler []func(c *Context)
Middleware []Handler
// HandlerAPI empty interface used for .API
HandlerAPI interface{}
)
// Serve implements the Handler, is like ServeHTTP but for Iris
func (h HandlerFunc) Serve(ctx *Context) {
h(ctx)
}
// ToHandler converts an httapi.Handler or http.HandlerFunc to an iris.Handler
func ToHandler(handler interface{}) Handler {
//this is not the best way to do it, but I dont have any options right now.
switch handler.(type) {
case Handler:
//it's already an iris handler
return handler.(Handler)
case http.Handler:
//it's http.Handler
h := fasthttpadaptor.NewFastHTTPHandlerFunc(handler.(http.Handler).ServeHTTP)
return ToHandlerFastHTTP(h)
case func(http.ResponseWriter, *http.Request):
//it's http.HandlerFunc
h := fasthttpadaptor.NewFastHTTPHandlerFunc(handler.(func(http.ResponseWriter, *http.Request)))
return ToHandlerFastHTTP(h)
default:
panic(errHandler.Format(handler, handler))
}
}
// ToHandlerFunc converts an http.Handler or http.HandlerFunc to an iris.HandlerFunc
func ToHandlerFunc(handler interface{}) HandlerFunc {
return ToHandler(handler).Serve
}
// ToHandlerFastHTTP converts an fasthttp.RequestHandler to an iris.Handler
func ToHandlerFastHTTP(h fasthttp.RequestHandler) Handler {
return HandlerFunc((func(ctx *Context) {
h(ctx.RequestCtx)
}))
}
// convertToHandlers just make []HandlerFunc to []Handler, although HandlerFunc and Handler are the same
// we need this on some cases we explicit want a interface Handler, it is useless for users.
func convertToHandlers(handlersFn []HandlerFunc) []Handler {
hlen := len(handlersFn)
mlist := make([]Handler, hlen)
for i := 0; i < hlen; i++ {
mlist[i] = Handler(handlersFn[i])
}
return mlist
}
// joinMiddleware uses to create a copy of all middleware and return them in order to use inside the node
func joinMiddleware(middleware1 Middleware, middleware2 Middleware) Middleware {
nowLen := len(middleware1)
totalLen := nowLen + len(middleware2)
// create a new slice of middleware in order to store all handlers, the already handlers(middleware) and the new
newMiddleware := make(Middleware, totalLen)
//copy the already middleware to the just created
copy(newMiddleware, middleware1)
//start from there we finish, and store the new middleware too
copy(newMiddleware[nowLen:], middleware2)
return newMiddleware
}
func profileMiddleware(debugPath string) Middleware {
htmlMiddleware := HandlerFunc(func(ctx *Context) {
ctx.SetContentType(contentHTML + "; charset=" + ctx.framework.Config.Charset)
ctx.Next()
})
indexHandler := ToHandlerFunc(pprof.Index)
cmdlineHandler := ToHandlerFunc(pprof.Cmdline)
profileHandler := ToHandlerFunc(pprof.Profile)
symbolHandler := ToHandlerFunc(pprof.Symbol)
goroutineHandler := ToHandlerFunc(pprof.Handler("goroutine"))
heapHandler := ToHandlerFunc(pprof.Handler("heap"))
threadcreateHandler := ToHandlerFunc(pprof.Handler("threadcreate"))
debugBlockHandler := ToHandlerFunc(pprof.Handler("block"))
return Middleware{htmlMiddleware, HandlerFunc(func(ctx *Context) {
action := ctx.Param("action")
if len(action) > 1 {
if strings.Contains(action, "cmdline") {
cmdlineHandler.Serve((ctx))
} else if strings.Contains(action, "profile") {
profileHandler.Serve(ctx)
} else if strings.Contains(action, "symbol") {
symbolHandler.Serve(ctx)
} else if strings.Contains(action, "goroutine") {
goroutineHandler.Serve(ctx)
} else if strings.Contains(action, "heap") {
heapHandler.Serve(ctx)
} else if strings.Contains(action, "threadcreate") {
threadcreateHandler.Serve(ctx)
} else if strings.Contains(action, "debug/block") {
debugBlockHandler.Serve(ctx)
}
} else {
indexHandler.Serve(ctx)
}
})}
}
const (
// parameterStartByte is very used on the node, it's just contains the byte for the ':' rune/char
parameterStartByte = byte(':')
// slashByte is just a byte of '/' rune/char
slashByte = byte('/')
// slash is just a string of "/"
slash = "/"
// matchEverythingByte is just a byte of '*" rune/char
matchEverythingByte = byte('*')
isStatic entryCase = iota
isRoot
hasParams
matchEverything
)
type (
// PathParameter is a struct which contains Key and Value, used for named path parameters
PathParameter struct {
Key string
Value string
}
// PathParameters type for a slice of PathParameter
// Tt's a slice of PathParameter type, because it's faster than map
PathParameters []PathParameter
// entryCase is the type which the type of muxEntryusing in order to determinate what type (parameterized, anything, static...) is the perticular node
entryCase uint8
// muxEntry is the node of a tree of the routes,
// in order to learn how this is working, google 'trie' or watch this lecture: https://www.youtube.com/watch?v=uhAUk63tLRM
// this method is used by the BSD's kernel also
muxEntry struct {
part string
entryCase entryCase
hasWildNode bool
tokens string
nodes []*muxEntry
middleware Middleware
precedence uint64
paramsLen uint8
}
)
var (
errMuxEntryConflictsWildcard = errors.New("Router: Path's part: '%s' conflicts with wildcard '%s' in the route path: '%s' !")
errMuxEntryMiddlewareAlreadyExists = errors.New("Router: Middleware were already registered for the path: '%s' !")
errMuxEntryInvalidWildcard = errors.New("Router: More than one wildcard found in the path part: '%s' in route's path: '%s' !")
errMuxEntryConflictsExistingWildcard = errors.New("Router: Wildcard for route path: '%s' conflicts with existing children in route path: '%s' !")
errMuxEntryWildcardUnnamed = errors.New("Router: Unnamed wildcard found in path: '%s' !")
errMuxEntryWildcardInvalidPlace = errors.New("Router: Wildcard is only allowed at the end of the path, in the route path: '%s' !")
errMuxEntryWildcardConflictsMiddleware = errors.New("Router: Wildcard conflicts with existing middleware for the route path: '%s' !")
errMuxEntryWildcardMissingSlash = errors.New("Router: No slash(/) were found before wildcard in the route path: '%s' !")
)
// Get returns a value from a key inside this Parameters
// If no parameter with this key given then it returns an empty string
func (params PathParameters) Get(key string) string {
for _, p := range params {
if p.Key == key {
return p.Value
}
}
return ""
}
// String returns a string implementation of all parameters that this PathParameters object keeps
// hasthe form of key1=value1,key2=value2...
func (params PathParameters) String() string {
var buff bytes.Buffer
for i := range params {
buff.WriteString(params[i].Key)
buff.WriteString("=")
buff.WriteString(params[i].Value)
if i < len(params)-1 {
buff.WriteString(",")
}
}
return buff.String()
}
// ParseParams receives a string and returns PathParameters (slice of PathParameter)
// received string must have this form: key1=value1,key2=value2...
func ParseParams(str string) PathParameters {
_paramsstr := strings.Split(str, ",")
if len(_paramsstr) == 0 {
return nil
}
params := make(PathParameters, 0) // PathParameters{}
// for i := 0; i < len(_paramsstr); i++ {
for i := range _paramsstr {
idxOfEq := strings.IndexRune(_paramsstr[i], '=')
if idxOfEq == -1 {
//error
return nil
}
key := _paramsstr[i][:idxOfEq]
val := _paramsstr[i][idxOfEq+1:]
params = append(params, PathParameter{key, val})
}
return params
}
// getParamsLen returns the parameters length from a given path
func getParamsLen(path string) uint8 {
var n uint
for i := 0; i < len(path); i++ {
if path[i] != ':' && path[i] != '*' { // ParameterStartByte & MatchEverythingByte
continue
}
n++
}
if n >= 255 {
return 255
}
return uint8(n)
}
// add adds a muxEntry to the existing muxEntry or to the tree if no muxEntry has the prefix of
func (e *muxEntry) add(path string, middleware Middleware) error {
fullPath := path
e.precedence++
numParams := getParamsLen(path)
if len(e.part) > 0 || len(e.nodes) > 0 {
loop:
for {
if numParams > e.paramsLen {
e.paramsLen = numParams
}
i := 0
max := utils.FindLower(len(path), len(e.part))
for i < max && path[i] == e.part[i] {
i++
}
if i < len(e.part) {
node := muxEntry{
part: e.part[i:],
hasWildNode: e.hasWildNode,
tokens: e.tokens,
nodes: e.nodes,
middleware: e.middleware,
precedence: e.precedence - 1,
}
for i := range node.nodes {
if node.nodes[i].paramsLen > node.paramsLen {
node.paramsLen = node.nodes[i].paramsLen
}
}
e.nodes = []*muxEntry{&node}
e.tokens = string([]byte{e.part[i]})
e.part = path[:i]
e.middleware = nil
e.hasWildNode = false
}
if i < len(path) {
path = path[i:]
if e.hasWildNode {
e = e.nodes[0]
e.precedence++
if numParams > e.paramsLen {
e.paramsLen = numParams
}
numParams--
if len(path) >= len(e.part) && e.part == path[:len(e.part)] {
if len(e.part) >= len(path) || path[len(e.part)] == slashByte {
continue loop
}
}
return errMuxEntryConflictsWildcard.Format(path, e.part, fullPath)
}
c := path[0]
if e.entryCase == hasParams && c == slashByte && len(e.nodes) == 1 {
e = e.nodes[0]
e.precedence++
continue loop
}
for i := range e.tokens {
if c == e.tokens[i] {
i = e.precedenceTo(i)
e = e.nodes[i]
continue loop
}
}
if c != parameterStartByte && c != matchEverythingByte {
e.tokens += string([]byte{c})
node := &muxEntry{
paramsLen: numParams,
}
e.nodes = append(e.nodes, node)
e.precedenceTo(len(e.tokens) - 1)
e = node
}
e.addNode(numParams, path, fullPath, middleware)
return nil
} else if i == len(path) {
if e.middleware != nil {
return errMuxEntryMiddlewareAlreadyExists.Format(fullPath)
}
e.middleware = middleware
}
return nil
}
} else {
e.addNode(numParams, path, fullPath, middleware)
e.entryCase = isRoot
}
return nil
}
// addNode adds a muxEntry as children to other muxEntry
func (e *muxEntry) addNode(numParams uint8, path string, fullPath string, middleware Middleware) error {
var offset int
for i, max := 0, len(path); numParams > 0; i++ {
c := path[i]
if c != parameterStartByte && c != matchEverythingByte {
continue
}
end := i + 1
for end < max && path[end] != slashByte {
switch path[end] {
case parameterStartByte, matchEverythingByte:
/*
panic("only one wildcard per path segment is allowed, has: '" +
path[i:] + "' in path '" + fullPath + "'")
*/
return errMuxEntryInvalidWildcard.Format(path[i:], fullPath)
default:
end++
}
}
if len(e.nodes) > 0 {
return errMuxEntryConflictsExistingWildcard.Format(path[i:end], fullPath)
}
if end-i < 2 {
return errMuxEntryWildcardUnnamed.Format(fullPath)
}
if c == parameterStartByte {
if i > 0 {
e.part = path[offset:i]
offset = i
}
child := &muxEntry{
entryCase: hasParams,
paramsLen: numParams,
}
e.nodes = []*muxEntry{child}
e.hasWildNode = true
e = child
e.precedence++
numParams--
if end < max {
e.part = path[offset:end]
offset = end
child := &muxEntry{
paramsLen: numParams,
precedence: 1,
}