-
Notifications
You must be signed in to change notification settings - Fork 37
/
air.go
1381 lines (1211 loc) · 40.2 KB
/
air.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 air implements an ideally refined web framework for Go.
Router
A router is basically the most important component of a web framework. In this
framework, registering a route usually requires at least two params:
air.Default.GET(
"/users/:UserID/posts/:PostID/assets/*",
func(req *air.Request, res *air.Response) error {
userID, err := req.Param("UserID").Value().Int64()
if err != nil {
return err
}
postID, err := req.Param("PostID").Value().Int64()
if err != nil {
return err
}
assetPath := req.Param("*").Value().String()
return res.WriteJSON(map[string]interface{}{
"user_id": userID,
"post_id": postID,
"asset_path": assetPath,
})
},
)
The first param is a route path that contains 6 components. Among them, "users",
"posts" and "assets" are STATIC components, ":UserID" and ":PostID" are PARAM
components, "*" is an ANY component. Note that all route params (PARAM and ANY
components) will be parsed into the `Request` and can be accessed via the
`Request.Param` and `Request.Params`. The name of a `RequestParam` parsed from a
PARAM component always discards its leading ":", such as ":UserID" will become
"UserID". The name of a `RequestParam` parsed from an ANY component is "*".
The second param is a `Handler` that serves the requests that match this route.
*/
package air
import (
"compress/gzip"
"context"
"crypto"
"crypto/tls"
"crypto/x509/pkix"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/mitchellh/mapstructure"
"github.com/pelletier/go-toml"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"gopkg.in/yaml.v3"
)
// Air is the top-level struct of this framework.
//
// It is highly recommended not to modify the value of any field of the `Air`
// after calling the `Air.Serve`, which will cause unpredictable problems.
//
// The new instances of the `Air` should only be created by calling the `New`.
// If you only need one instance of the `Air`, it is recommended to use the
// `Default`, which will help you simplify the scope management.
type Air struct {
// AppName is the name of the web application.
//
// It is recommended to set the `AppName` and try to ensure that it is
// unique (used to distinguish between different web applications).
//
// Default value: "air"
AppName string `mapstructure:"app_name"`
// MaintainerEmail is the e-mail address of the one who is responsible
// for maintaining the web application.
//
// It is recommended to set the `MaintainerEmail` if the `ACMEEnabled`
// is true (used by the CAs, such as Let's Encrypt, to notify about
// problems with issued certificates).
//
// Default value: ""
MaintainerEmail string `mapstructure:"maintainer_email"`
// DebugMode indicates whether the web application is in debug mode.
//
// Please keep in mind that the `DebugMode` is quite bossy, some
// features will be affected if it is true. So never set the `DebugMode`
// to true in a production environment unless you want to do something
// crazy.
//
// Default value: false
DebugMode bool `mapstructure:"debug_mode"`
// Address is the TCP address that the server listens on.
//
// The `Address` is never empty and contains a free port. If the port of
// the `Address` is "0", a random port is automatically chosen. The
// `Addresses` can be used to discover the chosen port.
//
// Default value: "localhost:8080"
Address string `mapstructure:"address"`
// ReadTimeout is the maximum duration allowed for the server to read a
// request entirely, including the body part.
//
// The `ReadTimeout` does not let the `Handler` make per-request
// decisions on each request body's acceptable deadline or upload rate.
//
// Default value: 0
ReadTimeout time.Duration `mapstructure:"read_timeout"`
// ReadHeaderTimeout is the maximum duration allowed for the server to
// read the headers of a request.
//
// The connection's read deadline is reset after reading the headers of
// a request and the `Handler` can decide what is considered too slow
// for the body.
//
// If the `ReadHeaderTimeout` is zero, the value of the `ReadTimeout` is
// used. If both are zero, there is no timeout.
//
// Default value: 0
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout"`
// WriteTimeout is the maximum duration allowed for the server to write
// a response.
//
// The `WriteTimeout` is reset whenever the headers of a new request are
// read. Like the `ReadTimeout`, the `WriteTimeout` does not let the
// `Handler` make decisions on a per-request basis.
//
// Default value: 0
WriteTimeout time.Duration `mapstructure:"write_timeout"`
// IdleTimeout is the maximum duration allowed for the server to wait
// for the next request.
//
// If the `IdleTimeout` is zero, the value of the `ReadTimeout` is used.
// If both are zero, there is no timeout.
//
// Default value: 0
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
// MaxHeaderBytes is the maximum number of bytes allowed for the server
// to read parsing the request headers' names and values, including
// HTTP/1.x request-line.
//
// Default value: 1048576
MaxHeaderBytes int `mapstructure:"max_header_bytes"`
// TLSConfig is the TLS configuration to make the server to handle
// requests on incoming TLS connections.
//
// Default value: nil
TLSConfig *tls.Config `mapstructure:"-"`
// TLSCertFile is the path to the TLS certificate file.
//
// The `TLSCertFile` must be set together wth the `TLSKeyFile`.
//
// If the certificate targeted by the `TLSCertFile` is signed by a CA,
// it should be the concatenation of the certificate, any intermediates,
// and the CA's certificate.
//
// If the `TLSConfig` is not nil, the certificate targeted by the
// `TLSCertFile` will be appended to the end of the `Certificates` of
// the `TLSConfig`'s clone. Otherwise, a new instance of the
// `tls.Config` will be created with the certificate.
//
// Default value: ""
TLSCertFile string `mapstructure:"tls_cert_file"`
// TLSKeyFile is the path to the TLS key file.
//
// The key targeted by the `TLSKeyFile` must match the certificate
// targeted by the `TLSCertFile`.
//
// Default value: ""
TLSKeyFile string `mapstructure:"tls_key_file"`
// ACMEEnabled indicates whether the ACME feature is enabled.
//
// The `ACMEEnabled` gives the server the ability to automatically
// obtain new certificates from the ACME CA.
//
// If the `TLSConfig` and `TLSConfig.GetCertificate` are not nil, the
// server will respect it and use the ACME feature as a backup.
// Otherwise, a new instance of the `tls.Config` will be created with
// the ACME feature.
//
// Default value: false
ACMEEnabled bool `mapstructure:"acme_enabled"`
// ACMEDirectoryURL is the ACME CA directory URL of the ACME feature.
//
// Default value: "https://acme-v02.api.letsencrypt.org/directory"
ACMEDirectoryURL string `mapstructure:"acme_directory_url"`
// ACMETOSURLWhitelist is the list of ACME CA's Terms of Service (TOS)
// URL allowed by the ACME feature.
//
// If the length of the `ACMETOSURLWhitelist` is zero, all TOS URLs will
// be allowed.
//
// Default value: nil
ACMETOSURLWhitelist []string `mapstructure:"acme_tos_url_whitelist"`
// ACMEAccountKey is the account key of the ACME feature used to
// register with an ACME CA and sign requests.
//
// Supported algorithms:
// * RS256
// * ES256
// * ES384
// * ES512
//
// If the `ACMEAccountKey` is nil, a new ECDSA P-256 key is generated.
//
// Default value: nil
ACMEAccountKey crypto.Signer `mapstructure:"-"`
// ACMECertRoot is the root of the certificates of the ACME feature.
//
// It is recommended to set the `ACMECertRoot` since all ACME CAs have a
// rate limit on issuing certificates. Different web applications can
// share the same place (if they are all built using this framework).
//
// Default value: "acme-certs"
ACMECertRoot string `mapstructure:"acme_cert_root"`
// ACMEHostWhitelist is the list of hosts allowed by the ACME feature.
//
// It is highly recommended to set the `ACMEHostWhitelist`. If the
// length of the `ACMEHostWhitelist` is not zero, all connections that
// are not connected to the hosts in it will not be able to obtain new
// certificates from the ACME CA.
//
// Default value: nil
ACMEHostWhitelist []string `mapstructure:"acme_host_whitelist"`
// ACMERenewalWindow is the renewal window of the ACME feature before a
// certificate expires.
//
// Default value: 2592000000000000
ACMERenewalWindow time.Duration `mapstructure:"acme_renewal_window"`
// ACMEExtraExts is the list of extra extensions used when generating a
// new CSR (Certificate Request), thus allowing customization of the
// resulting certificate.
//
// Default value: nil
ACMEExtraExts []pkix.Extension `mapstructure:"-"`
// HTTPSEnforced indicates whether the server is forcibly accessible
// only via the HTTPS scheme (HTTP requests will be automatically
// redirected to HTTPS).
//
// The `HTTPSEnforced` will always be treated as true when the
// `ACMEEnabled` is true.
//
// Default value: false
HTTPSEnforced bool `mapstructure:"https_enforced"`
// HTTPSEnforcedPort is the port of the TCP address (share the same host
// as the `Address`) that the server listens on. All requests to this
// port will be automatically redirected to HTTPS.
//
// If the `HTTPSEnforcedPort` is "0", a random port is automatically
// chosen. The `Addresses` can be used to discover the chosen port.
//
// Default value: "0"
HTTPSEnforcedPort string `mapstructure:"https_enforced_port"`
// WebSocketHandshakeTimeout is the maximum duration allowed for the
// server to wait for a WebSocket handshake to complete.
//
// Default value: 0
WebSocketHandshakeTimeout time.Duration `mapstructure:"websocket_handshake_timeout"`
// WebSocketSubprotocols is the list of supported WebSocket subprotocols
// of the server.
//
// If the length of the `WebSocketSubprotocols` is not zero, the
// `Response.WebSocket` negotiates a subprotocol by selecting the first
// match with a protocol requested by the client. If there is no match,
// no protocol is negotiated (the Sec-Websocket-Protocol header is not
// included in the handshake response).
//
// Default value: nil
WebSocketSubprotocols []string `mapstructure:"websocket_subprotocols"`
// PROXYEnabled indicates whether the PROXY feature is enabled.
//
// The `PROXYEnabled` gives the server the ability to support the PROXY
// protocol (See
// https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt).
//
// Default value: false
PROXYEnabled bool `mapstructure:"proxy_enabled"`
// PROXYReadHeaderTimeout is the maximum duration allowed for the server
// to read the PROXY protocol header of a connection.
//
// The connection's read deadline is reset after reading the PROXY
// protocol header.
//
// Default value: 0
PROXYReadHeaderTimeout time.Duration `mapstructure:"proxy_read_header_timeout"`
// PROXYRelayerIPWhitelist is the list of IP addresses or CIDR notation
// IP address ranges of the relayers allowed by the PROXY feature.
//
// It is highly recommended to set the `PROXYRelayerIPWhitelist`. If the
// length of the `PROXYRelayerIPWhitelist` is not zero, all connections
// relayed from the IP addresses are not in it will not be able to act
// the PROXY protocol.
//
// Default value: nil
PROXYRelayerIPWhitelist []string `mapstructure:"proxy_relayer_ip_whitelist"`
// Pregases is the `Gas` chain stack that performs before routing.
//
// The `Pregases` is always FILO.
//
// Default value: nil
Pregases []Gas `mapstructure:"-"`
// Gases is the `Gas` chain stack that performs after routing.
//
// The `Gases` is always FILO.
//
// Default value: nil
Gases []Gas `mapstructure:"-"`
// NotFoundHandler is the `Handler` that returns not found error.
//
// The `NotFoundHandler` is never nil because the router will use it as
// the default `Handler` when no match is found.
//
// Default value: `DefaultNotFoundHandler`
NotFoundHandler func(*Request, *Response) error `mapstructure:"-"`
// MethodNotAllowedHandler is the `Handler` that returns method not
// allowed error.
//
// The `MethodNotAllowedHandler` is never nil because the router will
// use it as the default `Handler` when a match is found but the request
// method is not registered.
//
// Default value: `DefaultMethodNotAllowedHandler`
MethodNotAllowedHandler func(*Request, *Response) error `mapstructure:"-"`
// ErrorHandler is the centralized error handler.
//
// The `ErrorHandler` is never nil because the server will use it in
// every request-response cycle that has an error.
//
// Default value: `DefaultErrorHandler`
ErrorHandler func(error, *Request, *Response) `mapstructure:"-"`
// ErrorLogger is the `log.Logger` that logs errors that occur in the
// web application.
//
// If the `ErrorLogger` is nil, logging is done via the log package's
// standard logger.
//
// Default value: nil
ErrorLogger *log.Logger `mapstructure:"-"`
// RendererTemplateRoot is the root of the HTML templates of the
// renderer feature.
//
// All HTML template files inside the `RendererTemplateRoot` will be
// recursively parsed into the renderer and their names will be used as
// HTML template names.
//
// Default value: "templates"
RendererTemplateRoot string `mapstructure:"renderer_template_root"`
// RendererTemplateExts is the list of filename extensions of the HTML
// templates of the renderer feature used to distinguish the HTML
// template files in the `RendererTemplateRoot`.
//
// Default value: [".html"]
RendererTemplateExts []string `mapstructure:"renderer_template_exts"`
// RendererTemplateLeftDelim is the left side of the HTML template
// delimiter of the renderer feature.
//
// default value: "{{"
RendererTemplateLeftDelim string `mapstructure:"renderer_template_left_delim"`
// RendererTemplateRightDelim is the right side of the HTML template
// delimiter of the renderer feature.
//
// Default value: "}}"
RendererTemplateRightDelim string `mapstructure:"renderer_template_right_delim"`
// RendererTemplateFuncMap is the HTML template function map of the
// renderer feature.
//
// The HTML template functions described in
// https://pkg.go.dev/text/template#hdr-Functions and the following are
// always available:
// * locstr
// Returns a localized string for its argument. It works exactly
// the same as the `Request.LocalizedString`
// * str2html
// Returns a `template.HTML` for its argument.
// * strlen
// Returns the number of characters of its argument.
// * substr
// Returns the substring consisting of the characters of its first
// argument starting at a start index (the second argument) and
// continuing up to, but not including, the character at an end
// index (the third argument).
// * timefmt
// Returns a textual representation of its first argument for the
// time layout (the second argument).
//
// Default value: nil
RendererTemplateFuncMap template.FuncMap `mapstructure:"-"`
// MinifierEnabled indicates whether the minifier feature is enabled.
//
// The `MinifierEnabled` gives the `Response.Write` the ability to
// minify the matching response body on the fly based on the
// Content-Type header.
//
// Default value: false
MinifierEnabled bool `mapstructure:"minifier_enabled"`
// MinifierMIMETypes is the list of MIME types of the minifier feature
// that will trigger the minimization.
//
// Supported MIME types:
// * text/html
// * text/css
// * application/javascript
// * application/json
// * application/xml
// * image/svg+xml
//
// Unsupported MIME types will be silently ignored.
//
// Default value: ["text/html", "text/css", "application/javascript",
// "application/json", "application/xml", "image/svg+xml"]
MinifierMIMETypes []string `mapstructure:"minifier_mime_types"`
// GzipEnabled indicates whether the gzip feature is enabled.
//
// The `GzipEnabled` gives the `Response` the ability to gzip the
// matching response body on the fly based on the Content-Type header.
//
// Default value: false
GzipEnabled bool `mapstructure:"gzip_enabled"`
// GzipMIMETypes is the list of MIME types of the gzip feature that will
// trigger the gzip.
//
// Default value: ["text/plain", "text/html", "text/css",
// "application/javascript", "application/json", "application/xml",
// "application/toml", "application/yaml", "image/svg+xml"]
GzipMIMETypes []string `mapstructure:"gzip_mime_types"`
// GzipCompressionLevel is the compression level of the gzip feature.
//
// Default value: `gzip.DefaultCompression`
GzipCompressionLevel int `mapstructure:"gzip_compression_level"`
// GzipMinContentLength is the minimum content length of the gzip
// featrue used to limit at least how big (determined only from the
// Content-Length header) response body can be gzipped.
//
// Default value: 1024
GzipMinContentLength int64 `mapstructure:"gzip_min_content_length"`
// CofferEnabled indicates whether the coffer feature is enabled.
//
// The `CofferEnabled` gives the `Response.WriteFile` the ability to use
// the runtime memory to reduce the disk I/O pressure.
//
// Default value: false
CofferEnabled bool `mapstructure:"coffer_enabled"`
// CofferMaxMemoryBytes is the maximum number of bytes of the runtime
// memory allowed for the coffer feature to use.
//
// Default value: 33554432
CofferMaxMemoryBytes int `mapstructure:"coffer_max_memory_bytes"`
// CofferAssetRoot is the root of the assets of the coffer feature.
//
// All asset files inside the `CofferAssetRoot` will be recursively
// parsed into the coffer and their names will be used as asset names.
//
// Default value: "assets"
CofferAssetRoot string `mapstructure:"coffer_asset_root"`
// CofferAssetExts is the list of filename extensions of the assets of
// the coffer feature used to distinguish the asset files in the
// `CofferAssetRoot`.
//
// Default value: [".html", ".css", ".js", ".json", ".xml", ".toml",
// ".yaml", ".yml", ".svg", ".jpg", ".jpeg", ".png", ".gif"]
CofferAssetExts []string `mapstructure:"coffer_asset_exts"`
// I18nEnabled indicates whether the i18n feature is enabled.
//
// The `I18nEnabled` gives the `Request.LocalizedString` and
// `Response.Render` the ability to adapt to the request's favorite
// conventions based on the Accept-Language header.
//
// Default value: false
I18nEnabled bool `mapstructure:"i18n_enabled"`
// I18nLocaleRoot is the root of the locales of the i18n feature.
//
// All TOML-based locale files (".toml" is the extension) inside the
// `I18nLocaleRoot` will be parsed into the i18n and their names
// (without extension) will be used as locales.
//
// Default value: "locales"
I18nLocaleRoot string `mapstructure:"i18n_locale_root"`
// I18nLocaleBase is the base of the locales of the i18n feature used
// when a locale cannot be found.
//
// Default value: "en-US"
I18nLocaleBase string `mapstructure:"i18n_locale_base"`
// ConfigFile is the path to the configuration file that will be parsed
// into the matching fields before starting the server.
//
// The ".json" extension means the configuration file is JSON-based.
//
// The ".toml" extension means the configuration file is TOML-based.
//
// The ".yaml" and ".yml" extensions means the configuration file is
// YAML-based.
//
// Default value: ""
ConfigFile string `mapstructure:"-"`
server *http.Server
router *router
binder *binder
renderer *renderer
minifier *minifier
coffer *coffer
i18n *i18n
context context.Context
contextCancel context.CancelFunc
addressMap map[string]int
shutdownJobs []func()
shutdownJobMutex sync.Mutex
shutdownJobDone chan struct{}
requestPool sync.Pool
responsePool sync.Pool
contentTypeSnifferBufferPool sync.Pool
gzipWriterPool sync.Pool
reverseProxyTransport *reverseProxyTransport
reverseProxyBufferPool *reverseProxyBufferPool
}
// Default is the default instance of the `Air`.
//
// If you only need one instance of the `Air`, you should use the `Default`.
// Unless you think you can efficiently pass your instance in different scopes.
var Default = New()
// New returns a new instance of the `Air` with default field values.
//
// The `New` is the only function that creates new instances of the `Air` and
// keeps everything working.
func New() *Air {
a := &Air{
AppName: "air",
Address: "localhost:8080",
MaxHeaderBytes: 1 << 20,
ACMEDirectoryURL: "https://acme-v02.api.letsencrypt.org/directory",
ACMECertRoot: "acme-certs",
ACMERenewalWindow: 30 * 24 * time.Hour,
HTTPSEnforcedPort: "0",
NotFoundHandler: DefaultNotFoundHandler,
MethodNotAllowedHandler: DefaultMethodNotAllowedHandler,
ErrorHandler: DefaultErrorHandler,
MinifierMIMETypes: []string{
"text/html",
"text/css",
"application/javascript",
"application/json",
"application/xml",
"image/svg+xml",
},
GzipMIMETypes: []string{
"text/plain",
"text/html",
"text/css",
"application/javascript",
"application/json",
"application/xml",
"application/toml",
"application/yaml",
"image/svg+xml",
},
GzipCompressionLevel: gzip.DefaultCompression,
GzipMinContentLength: 1 << 10,
RendererTemplateRoot: "templates",
RendererTemplateExts: []string{".html"},
RendererTemplateLeftDelim: "{{",
RendererTemplateRightDelim: "}}",
CofferMaxMemoryBytes: 32 << 20,
CofferAssetRoot: "assets",
CofferAssetExts: []string{
".html",
".css",
".js",
".json",
".xml",
".toml",
".yaml",
".yml",
".svg",
".jpg",
".jpeg",
".png",
".gif",
},
I18nLocaleRoot: "locales",
I18nLocaleBase: "en-US",
}
a.server = &http.Server{}
a.router = newRouter(a)
a.binder = newBinder(a)
a.renderer = newRenderer(a)
a.minifier = newMinifier(a)
a.coffer = newCoffer(a)
a.i18n = newI18n(a)
a.context, a.contextCancel = context.WithCancel(context.Background())
a.addressMap = map[string]int{}
a.shutdownJobDone = make(chan struct{})
a.requestPool.New = func() interface{} {
return &Request{}
}
a.responsePool.New = func() interface{} {
return &Response{}
}
a.contentTypeSnifferBufferPool.New = func() interface{} {
return make([]byte, 512)
}
a.gzipWriterPool.New = func() interface{} {
w, _ := gzip.NewWriterLevel(nil, a.GzipCompressionLevel)
return w
}
a.reverseProxyTransport = newReverseProxyTransport()
a.reverseProxyBufferPool = newReverseProxyBufferPool()
return a
}
// GET registers a new GET route for the path with the matching h in the router
// of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) GET(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodGet, path, h, gases...)
}
// HEAD registers a new HEAD route for the path with the matching h in the
// router of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) HEAD(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodHead, path, h, gases...)
}
// POST registers a new POST route for the path with the matching h in the
// router of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) POST(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodPost, path, h, gases...)
}
// PUT registers a new PUT route for the path with the matching h in the router
// of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) PUT(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodPut, path, h, gases...)
}
// PATCH registers a new PATCH route for the path with the matching h in the
// router of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) PATCH(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodPatch, path, h, gases...)
}
// DELETE registers a new DELETE route for the path with the matching h in the
// router of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) DELETE(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodDelete, path, h, gases...)
}
// CONNECT registers a new CONNECT route for the path with the matching h in the
// router of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) CONNECT(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodConnect, path, h, gases...)
}
// OPTIONS registers a new OPTIONS route for the path with the matching h in the
// router of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) OPTIONS(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodOptions, path, h, gases...)
}
// TRACE registers a new TRACE route for the path with the matching h in the
// router of the a with the optional route-level gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) TRACE(path string, h Handler, gases ...Gas) {
a.router.register(http.MethodTrace, path, h, gases...)
}
// BATCH registers a batch of routes for the methods and path with the matching
// h in the router of the a with the optional route-level gases.
//
// The methods must either be nil (means all) or consists of one or more of the
// "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS" and
// "TRACE". Invalid methods will be silently ignored.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) BATCH(methods []string, path string, h Handler, gases ...Gas) {
if methods == nil {
methods = []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
}
for _, m := range methods {
switch m {
case http.MethodGet:
a.GET(path, h, gases...)
case http.MethodHead:
a.HEAD(path, h, gases...)
case http.MethodPost:
a.POST(path, h, gases...)
case http.MethodPut:
a.PUT(path, h, gases...)
case http.MethodPatch:
a.PATCH(path, h, gases...)
case http.MethodDelete:
a.DELETE(path, h, gases...)
case http.MethodConnect:
a.CONNECT(path, h, gases...)
case http.MethodOptions:
a.OPTIONS(path, h, gases...)
case http.MethodTrace:
a.TRACE(path, h, gases...)
}
}
}
// FILE registers a new GET and HEAD route pair with the path in the router of
// the a to serve a static file with the filename and optional route-level
// gases.
//
// The path may consist of STATIC, PARAM and ANY components.
//
// The gases is always FILO.
func (a *Air) FILE(path, filename string, gases ...Gas) {
h := func(req *Request, res *Response) error {
err := res.WriteFile(filename)
if os.IsNotExist(err) {
return a.NotFoundHandler(req, res)
}
return err
}
a.BATCH([]string{http.MethodGet, http.MethodHead}, path, h, gases...)
}
// FILES registers some new GET and HEAD route paris with the path prefix in the
// router of the a to serve the static files from the root with the optional
// route-level gases.
//
// The prefix may consit of STATIC and PARAM components, but it must not contain
// ANY component.
//
// The gases is always FILO.
func (a *Air) FILES(prefix, root string, gases ...Gas) {
if strings.HasSuffix(prefix, "/") {
prefix += "*"
} else {
prefix += "/*"
}
if root == "" {
root = "."
}
h := func(req *Request, res *Response) error {
path := req.Param("*").Value().String()
path = filepath.FromSlash(fmt.Sprint("/", path))
path = filepath.Clean(path)
err := res.WriteFile(filepath.Join(root, path))
if os.IsNotExist(err) {
return a.NotFoundHandler(req, res)
}
return err
}
a.BATCH([]string{http.MethodGet, http.MethodHead}, prefix, h, gases...)
}
// Group returns a new instance of the `Group` with the path prefix and optional
// group-level gases that inherited from the a.
//
// The prefix may consit of STATIC and PARAM components, but it must not contain
// ANY component.
//
// The gases is always FILO.
func (a *Air) Group(prefix string, gases ...Gas) *Group {
return &Group{
Air: a,
Prefix: prefix,
Gases: gases,
}
}
// Serve starts the server of the a.
func (a *Air) Serve() error {
if a.ConfigFile != "" {
b, err := ioutil.ReadFile(a.ConfigFile)
if err != nil {
return err
}
m := map[string]interface{}{}
switch e := strings.ToLower(filepath.Ext(a.ConfigFile)); e {
case ".json":
err = json.Unmarshal(b, &m)
case ".toml":
err = toml.Unmarshal(b, &m)
case ".yaml", ".yml":
err = yaml.Unmarshal(b, &m)
default:
err = fmt.Errorf(
"air: unsupported configuration file "+
"extension: %s",
e,
)
}
if err != nil {
return err
} else if err := mapstructure.Decode(m, a); err != nil {
return err
}
}
host, port, err := net.SplitHostPort(a.Address)
if err != nil {
return err
}
a.server.Addr = net.JoinHostPort(host, port)
a.server.Handler = a
a.server.ReadTimeout = a.ReadTimeout
a.server.ReadHeaderTimeout = a.ReadHeaderTimeout
a.server.WriteTimeout = a.WriteTimeout
a.server.IdleTimeout = a.IdleTimeout
a.server.MaxHeaderBytes = a.MaxHeaderBytes
a.server.ErrorLog = a.ErrorLogger
tlsConfig := a.TLSConfig
if tlsConfig != nil {
tlsConfig = tlsConfig.Clone()
}
if a.TLSCertFile != "" && a.TLSKeyFile != "" {
c, err := tls.LoadX509KeyPair(a.TLSCertFile, a.TLSKeyFile)
if err != nil {
return err
}
if tlsConfig == nil {
tlsConfig = &tls.Config{}
}
tlsConfig.Certificates = append(tlsConfig.Certificates, c)
}
if tlsConfig != nil {
for _, proto := range []string{"h2", "http/1.1"} {
if !stringSliceContains(
tlsConfig.NextProtos,
proto,
false,
) {
tlsConfig.NextProtos = append(
tlsConfig.NextProtos,
proto,
)
}
}
}
hh := http.Handler(http.HandlerFunc(func(
rw http.ResponseWriter,
r *http.Request,
) {
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
host = r.Host
}
if port != "443" {
host = net.JoinHostPort(host, port)
}
http.Redirect(
rw,
r,
fmt.Sprint("https://", host, r.RequestURI),
http.StatusMovedPermanently,
)
}))
if a.ACMEEnabled {
acm := &autocert.Manager{
Prompt: func(tosURL string) bool {
if len(a.ACMETOSURLWhitelist) == 0 {
return true
}