-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconfig.go
More file actions
211 lines (183 loc) · 5.89 KB
/
config.go
File metadata and controls
211 lines (183 loc) · 5.89 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
package httpserver
import (
"context"
"crypto/tls"
"fmt"
"math"
"net/http"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/Vonage/gosrvlib/pkg/ipify"
"github.com/Vonage/gosrvlib/pkg/logging"
"github.com/Vonage/gosrvlib/pkg/profiling"
"github.com/Vonage/gosrvlib/pkg/redact"
"github.com/Vonage/gosrvlib/pkg/traceid"
"github.com/julienschmidt/httprouter"
"go.uber.org/zap"
)
const timeoutMessage = "TIMEOUT"
// RedactFn is an alias for a redact function.
type RedactFn func(s string) string
// IndexHandlerFunc is a type alias for the route index function.
type IndexHandlerFunc func([]Route) http.HandlerFunc
// GetPublicIPFunc is a type alias for function to get public IP of the service.
type GetPublicIPFunc func(context.Context) (string, error)
// GetPublicIPDefaultFunc returns the GetPublicIP function for a default ipify client.
func GetPublicIPDefaultFunc() GetPublicIPFunc {
c, _ := ipify.New() // no errors are returned with default values
return c.GetPublicIP
}
type config struct {
router *httprouter.Router
serverAddr string
traceIDHeaderName string
requestTimeout time.Duration
serverReadHeaderTimeout time.Duration
serverReadTimeout time.Duration
serverWriteTimeout time.Duration
shutdownTimeout time.Duration
tlsConfig *tls.Config
defaultEnabledRoutes []DefaultRoute
indexHandlerFunc IndexHandlerFunc
ipHandlerFunc http.HandlerFunc
metricsHandlerFunc http.HandlerFunc
pingHandlerFunc http.HandlerFunc
pprofHandlerFunc http.HandlerFunc
statusHandlerFunc http.HandlerFunc
notFoundHandlerFunc http.HandlerFunc
methodNotAllowedHandlerFunc http.HandlerFunc
panicHandlerFunc http.HandlerFunc
redactFn RedactFn
middleware []MiddlewareFn
disableDefaultRouteLogger map[DefaultRoute]bool
disableRouteLogger bool
shutdownWaitGroup *sync.WaitGroup
shutdownSignalChan chan struct{}
}
func defaultConfig() *config {
return &config{
router: httprouter.New(),
serverAddr: ":8017",
traceIDHeaderName: traceid.DefaultHeader,
serverReadHeaderTimeout: 1 * time.Minute,
serverReadTimeout: 1 * time.Minute,
serverWriteTimeout: 1 * time.Minute,
shutdownTimeout: 30 * time.Second,
defaultEnabledRoutes: nil,
indexHandlerFunc: defaultIndexHandler,
ipHandlerFunc: defaultIPHandler(GetPublicIPDefaultFunc()),
metricsHandlerFunc: notImplementedHandler,
pingHandlerFunc: defaultPingHandler,
pprofHandlerFunc: profiling.PProfHandler,
statusHandlerFunc: defaultStatusHandler,
notFoundHandlerFunc: defaultNotFoundHandlerFunc,
methodNotAllowedHandlerFunc: defaultMethodNotAllowedHandlerFunc,
panicHandlerFunc: defaultPanicHandlerFunc,
redactFn: redact.HTTPData,
middleware: []MiddlewareFn{},
disableDefaultRouteLogger: make(map[DefaultRoute]bool, len(allDefaultRoutes())),
shutdownWaitGroup: &sync.WaitGroup{},
shutdownSignalChan: make(chan struct{}),
}
}
func (c *config) isIndexRouteEnabled() bool {
for _, r := range c.defaultEnabledRoutes {
if r == IndexRoute {
return true
}
}
return false
}
// validateAddr checks if a http server bind address is valid.
func validateAddr(addr string) error {
addrErr := fmt.Errorf("invalid http server address: %s", addr)
if !strings.Contains(addr, ":") {
return addrErr
}
parts := strings.Split(addr, ":")
if len(parts) != 2 {
return addrErr
}
port := parts[1]
if port == "" {
return addrErr
}
portInt, err := strconv.Atoi(port)
if err != nil {
return addrErr
}
if portInt < 1 || portInt > math.MaxUint16 {
return addrErr
}
return nil
}
func (c *config) commonMiddleware(noRouteLogger bool, rTimeout time.Duration) []MiddlewareFn {
middleware := []MiddlewareFn{}
if !c.disableRouteLogger && !noRouteLogger {
middleware = append(middleware, LoggerMiddlewareFn)
}
timeout := c.requestTimeout
if rTimeout > 0 {
timeout = rTimeout
}
if timeout > 0 {
timeoutMiddlewareFn := func(_ MiddlewareArgs, next http.Handler) http.Handler {
return http.TimeoutHandler(next, timeout, timeoutMessage)
}
middleware = append(middleware, timeoutMiddlewareFn)
}
return append(middleware, c.middleware...)
}
func (c *config) setRouter(ctx context.Context) {
l := logging.FromContext(ctx)
middleware := c.commonMiddleware(false, 0)
if c.router.NotFound == nil {
c.router.NotFound = ApplyMiddleware(
MiddlewareArgs{
Path: "404",
Description: http.StatusText(http.StatusNotFound),
TraceIDHeaderName: c.traceIDHeaderName,
RedactFunc: c.redactFn,
Logger: l,
},
c.notFoundHandlerFunc,
middleware...,
)
}
if c.router.MethodNotAllowed == nil {
c.router.MethodNotAllowed = ApplyMiddleware(
MiddlewareArgs{
Path: "405",
Description: http.StatusText(http.StatusMethodNotAllowed),
TraceIDHeaderName: c.traceIDHeaderName,
RedactFunc: c.redactFn,
Logger: l,
},
c.methodNotAllowedHandlerFunc,
middleware...,
)
}
if c.router.PanicHandler == nil {
c.router.PanicHandler = func(w http.ResponseWriter, r *http.Request, p any) {
logging.FromContext(r.Context()).Error(
"panic",
zap.Any("err", p),
zap.String("stacktrace", string(debug.Stack())),
)
ApplyMiddleware(
MiddlewareArgs{
Path: "500",
Description: http.StatusText(http.StatusInternalServerError),
TraceIDHeaderName: c.traceIDHeaderName,
RedactFunc: c.redactFn,
Logger: l,
},
c.panicHandlerFunc,
middleware...,
).ServeHTTP(w, r)
}
}
}