This repository was archived by the owner on Apr 11, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathhttpsvr.go
More file actions
283 lines (255 loc) · 8.55 KB
/
Copy pathhttpsvr.go
File metadata and controls
283 lines (255 loc) · 8.55 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
// Package httpsvr supports a router that understand http method and url params
// (features that standard http_ServeMux lacked).
// This package can be configured to log all pairs of request/response by adding an
// auto-generated requestId to the request_Context. This package also monitors
// number of requests for each handler, requests duration percentile.
package httpsvr
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sort"
"time"
"github.com/julienschmidt/httprouter"
"github.com/mywrap/gofast"
"github.com/mywrap/log"
"github.com/mywrap/metric"
)
// Server must be inited by calling func NewServer
type Server struct {
// config defines parameters for running an HTTP server,
// usually user should set ReadHeaderTimeout, ReadTimeout, WriteTimeout,
// ReadTimeout and WriteTimeout should be bigger for a file server
config *http.Server
// func Server.AddHandler is usually enough to declare routing rules,
// but sometimes we need to call Server.Router.ServeHTTP in test code or
// Server.Router.ServeFiles
Router *httprouter.Router
isEnableLog bool // default NewServer set isEnableLog = true, should be disabled if performance is an issue
isEnableMetric bool // default NewServer set isEnableMetric = true
Metric metric.Metric // default is an in-memory metric, reset daily
}
// NewServer init a Server with my recommended settings.
// For more customizable server, use NewServerWithConf instead.
func NewServer() *Server {
router := httprouter.New()
config := NewDefaultConfig()
config.Handler = router
s := &Server{
config: config,
isEnableLog: true,
isEnableMetric: true,
Router: router,
Metric: metric.NewMemoryMetric(),
}
gofast.NewCron(s.Metric.Reset, 24*time.Hour, 0)
s.AddHandler("GET", "/__metric", s.HandleMetric())
return s
}
// NewServerWithConf is used for turning off log, turning off metric
// or providing a persistent metric instead of in-memory.
// Usually, using simple func NewServer is enough.
func NewServerWithConf(conf *http.Server, isLog bool, metric0 metric.Metric) *Server {
if conf == nil {
conf = NewDefaultConfig()
}
router := httprouter.New()
conf.Handler = router
s := &Server{
config: conf,
isEnableLog: isLog,
isEnableMetric: !gofast.CheckNilInterface(metric0),
Router: router,
Metric: metric0,
}
return s
}
// AddHandler defines the router. Ex: AddHandler("GET", "/", ExampleHandler()).
// The router matches the URL of each incoming request against a list of
// registered path/method patterns and calls the handler for the pattern.
func (s *Server) AddHandler(method string, path string, handler http.HandlerFunc) {
defer func() { // in case of adding a same handler twice
if r := recover(); r != nil {
log.Infof("error when AddHandler: %v", r)
}
}()
// be careful with augmenting handler, example of stack overflow:
// f := func() { log.Println("f called") }
// f = func() { f() }
// f()
var augmented1 http.HandlerFunc
if !s.isEnableMetric {
augmented1 = handler
} else {
augmented1 = s.augmentMetric(method, path, handler)
}
var augmented2 http.HandlerFunc
if !s.isEnableLog {
augmented2 = augmented1
} else {
augmented2 = s.augmentLog(augmented1)
}
s.Router.HandlerFunc(method, path, augmented2)
}
// AddHandlerNotFound will be called when no matching route is found,
// example usage: the server echos every request to the client regardless of path or method
func (s *Server) AddHandlerNotFound(handler http.HandlerFunc) {
var augmented1 http.HandlerFunc
if !s.isEnableMetric {
augmented1 = handler
} else {
augmented1 = s.augmentMetric("", "", handler)
}
var augmented2 http.HandlerFunc
if !s.isEnableLog {
augmented2 = augmented1
} else {
augmented2 = s.augmentLog(augmented1)
}
s.Router.NotFound = augmented2
}
func (s *Server) augmentMetric(method string, path string,
handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var metricKey string
if method != "" && path != "" {
metricKey = fmt.Sprintf("%v_%v", path, method)
} else {
metricKey = fmt.Sprintf("%v_%v", r.URL.Path, r.Method)
}
s.Metric.Count(metricKey)
beginTime := time.Now()
handler(w, r)
s.Metric.Duration(metricKey, time.Since(beginTime))
}
}
func (s *Server) augmentLog(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestId := gofast.UUIDGenNoHyphen()
ctx := context.WithValue(r.Context(), CtxRequestId, requestId)
query := r.URL.Query().Encode()
if query != "" {
query = "?" + query
}
log.Condf(s.isEnableLog, "http request %v from %v: %v %v%v",
requestId, r.RemoteAddr, r.Method, r.URL.Path, query)
handler(w, r.WithContext(ctx))
log.Condf(s.isEnableLog, "http responded %v to %v: %v %v%v",
requestId, r.RemoteAddr, r.Method, r.URL.Path, query)
}
}
// ListenAndServe listens on input TCP network address addr
func (s *Server) ListenAndServe(addr string) error {
s.config.Addr = addr
return s.config.ListenAndServe()
}
// ListenAndServe2 listens on the port that defined in the Server.config.Addr
func (s *Server) ListenAndServe2() error {
return s.ListenAndServe(s.config.Addr)
}
// ListenAndServeTLS listens on the port that defined in the Server.config.Addr
func (s *Server) ListenAndServeTLS(addr string, certFile, keyFile string) error {
s.config.Addr = addr
return s.config.ListenAndServeTLS(certFile, keyFile)
}
// NewDefaultConfig is my suggestion of a http server config,
// feel free to modified base on your circumstance
func NewDefaultConfig() *http.Server {
return &http.Server{
ReadHeaderTimeout: 60 * time.Second,
ReadTimeout: 10 * time.Minute,
WriteTimeout: 20 * time.Minute,
}
}
// GetUrlParams returns URL parameters from a http request as a map,
// ex: path `/match/:id` has param `id`
func GetUrlParams(r *http.Request) map[string]string {
params := httprouter.ParamsFromContext(r.Context())
result := make(map[string]string, len(params))
if len(params) == 0 {
return result
}
for _, param := range params {
result[param.Key] = param.Value
}
return result
}
//
// utility
//
// Write is a utility to respond body with logging
func (s *Server) Write(w http.ResponseWriter, r *http.Request, body string) (
int, error) {
n, err := w.Write([]byte(body))
if err != nil { // will never happen
log.Condf(s.isEnableLog, "error Write %v: %v",
GetRequestId(r), err)
return n, err
}
log.Condf(s.isEnableLog, "http write body %v: %v",
GetRequestId(r), body)
return n, nil
}
// WriteJson is a utility to respond body with logging
func (s *Server) WriteJson(w http.ResponseWriter, r *http.Request, obj interface{}) (
int, error) {
bodyB, err := json.Marshal(obj)
if err != nil {
log.Condf(s.isEnableLog, "error WriteJson %v: %v",
GetRequestId(r), err)
http.Error(w, err.Error(), 500)
return 0, err
}
n, err := w.Write(bodyB)
if err != nil { // will never happen
log.Condf(s.isEnableLog, "error WriteJson %v: %v",
GetRequestId(r), err)
return n, err
}
log.Condf(s.isEnableLog, "http write body %v: %s",
GetRequestId(r), bodyB)
return n, nil
}
// ReadJson is a utility to parse request json body
func (s *Server) ReadJson(r *http.Request, outPtr interface{}) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
log.Condf(s.isEnableLog, "http request body %v: %s", GetRequestId(r), body)
err = json.Unmarshal(body, outPtr)
return err
}
func (s *Server) HandleMetric() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentMetric := s.Metric.GetCurrentMetric()
sort.Sort(metric.SortByAveDur(currentMetric))
beauty, _ := json.MarshalIndent(currentMetric, "", "\t")
w.Write(beauty)
}
}
var emptyServer = &Server{isEnableLog: true}
// Write is a utility to respond body with logging
func Write(w http.ResponseWriter, r *http.Request, body string) (
int, error) {
return emptyServer.Write(w, r, body)
}
// WriteJson is a utility to respond body with logging
func WriteJson(w http.ResponseWriter, r *http.Request, obj interface{}) (
int, error) {
return emptyServer.WriteJson(w, r, obj)
}
// ReadJson is a utility to parse request json body with logging
func ReadJson(r *http.Request, outPtr interface{}) error {
return emptyServer.ReadJson(r, outPtr)
}
// GetRequestId returns the auto generated unique requestId
func GetRequestId(r *http.Request) string {
return fmt.Sprintf("%v", r.Context().Value(CtxRequestId))
}
// ctxKeyType is used for avoiding context key conflict
type ctxKeyType string
// CtxRequestId is a internal request id
const CtxRequestId ctxKeyType = "CtxRequestId"