-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmux.go
More file actions
70 lines (56 loc) · 1.35 KB
/
mux.go
File metadata and controls
70 lines (56 loc) · 1.35 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
package httpx
import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/unrolled/secure"
)
// MuxOptions allow mux configuration.
type MuxOptions struct {
Env Env
Logger middleware.LogFormatter
Secure *secure.Options
CORS *cors.Options
Heartbeat string // heartbeat path, set to "false" to disable
NoCompress bool // disable compression
}
func (o *MuxOptions) norm() {
if o.Env == unknownEnv {
o.Env = guessedEnv
}
if o.Logger == nil {
o.Logger = &middleware.DefaultLogFormatter{Logger: newStdLogger(o.Env)}
}
if o.Secure == nil {
o.Secure = secureDefaults(o.Env)
}
if o.CORS == nil {
o.CORS = corsDefaults(o.Env)
}
if o.Heartbeat == "" {
o.Heartbeat = coalesce(fromEnv("HTTP_HEARTBEAT"), "/ping")
}
o.NoCompress = fromEnv("HTTP_COMPRESS") == "false"
}
// NewMux inits a new *chi.Mux with options
func NewMux(opt *MuxOptions) *chi.Mux {
var o MuxOptions
if opt != nil {
o = *opt
}
o.norm()
r := chi.NewMux()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
if o.Heartbeat != "false" {
r.Use(middleware.Heartbeat(o.Heartbeat))
}
r.Use(middleware.RequestLogger(o.Logger))
r.Use(middleware.Recoverer)
r.Use(secure.New(*o.Secure).Handler)
r.Use(cors.New(*o.CORS).Handler)
if !o.NoCompress {
r.Use(middleware.Compress(2))
}
return r
}