/
server.go
433 lines (385 loc) · 13.5 KB
/
server.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
package stgin
import (
"encoding/json"
"fmt"
"github.com/AminMal/slogger/colored"
"net/http"
"time"
"mime/multipart"
"strings"
)
var defaultController *Controller = NewController("Server", "")
// Server is the starting point of stgin applications, which holds the address, controllers, APIs and server-level listeners.
// Which can be run on the specified address.
type Server struct {
addr string
Controllers []*Controller
requestListeners []RequestListener
responseListeners []ResponseListener
apiListeners []APIListener
notFoundAction API
errorAction ErrorHandler
interrupts []Interrupt
}
// Register appends given controllers to the server.
func (server *Server) Register(controllers ...*Controller) {
server.Controllers = append(server.Controllers, controllers...)
}
// AddRoutes is an alternative to controller.AddRoutes, which adds the given routes to the server's default controller.
func (server *Server) AddRoutes(routes ...Route) {
for _, c := range server.Controllers {
if c == defaultController {
c.AddRoutes(routes...)
break
}
}
}
// CorsHandler function takes the responsibility to handle requests with "OPTIONS" method with the given headers in handler parameter.
func (server *Server) CorsHandler(handler CorsHandler) {
server.AddRoutes(OPTIONS(Prefix(""), func(RequestContext) Status {
return Ok(Empty()).WithHeaders(http.Header{
"Access-Control-Allow-Origin": []string{strings.Join(handler.AllowOrigin, ", ")},
"Access-Control-Allow-Credentials": []string{strings.Join(handler.AllowCredentials, ", ")},
"Access-Control-Allow-Headers": []string{strings.Join(handler.AllowHeaders, ", ")},
"Access-Control-Allow-Methods": []string{strings.Join(handler.AllowMethods, ", ")},
})
}))
}
// AddRequestListeners adds the given request listeners to server-level
// listeners (which then will be applied to all the incoming requests).
func (server *Server) AddRequestListeners(listeners ...RequestListener) {
server.requestListeners = append(server.requestListeners, listeners...)
}
// AddResponseListeners adds the given response listeners to server-level
// listeners (which then will be applied to all the outgoing responses).
func (server *Server) AddResponseListeners(listeners ...ResponseListener) {
server.responseListeners = append(server.responseListeners, listeners...)
}
// AddAPIListeners adds the given api listeners to server-level
// listeners (which then will be applied to all the incoming requests and outgoing responses after they're finished).
func (server *Server) AddAPIListeners(listeners ...APIListener) {
server.apiListeners = append(server.apiListeners, listeners...)
}
// NotFoundAction defines what server should do with the requests that match no routes.
func (server *Server) NotFoundAction(action API) {
server.notFoundAction = action
}
// SetErrorHandler defines what server should do in case some api panics.
func (server *Server) SetErrorHandler(action ErrorHandler) {
server.errorAction = action
}
// SetTimeout registers a timeout interrupt to the server
func (server *Server) SetTimeout(dur time.Duration) {
server.RegisterInterrupts(TimeoutInterrupt(dur))
}
// RegisterInterrupts adds the given interrupts to the server's already existing interrupts
func (server *Server) RegisterInterrupts(interrupts ...Interrupt) {
server.interrupts = append(server.interrupts, interrupts...)
}
func catchErrInto(errChan chan interface{}) {
if err := recover(); err != nil {
errChan <- err
}
}
func executeInterrupts(interrupts []Interrupt, request RequestContext, completeWith chan *Status) {
for _, interrupt := range interrupts {
go interrupt.TriggerFor(request, completeWith)
}
}
// translate is a function which takes stgin specifications about user defined APIs,
// and is responsible to translate it into the lower-level base package(currently net/http).
func translate(
api API,
requestListeners []RequestListener,
responseListeners []ResponseListener,
apiListeners []APIListener,
recovery ErrorHandler,
pathParams Params,
interrupts []Interrupt,
) http.HandlerFunc {
panicChannel := make(chan interface{}, 1)
successfulResultChannel := make(chan *Status, 1)
interruptChannel := make(chan *Status, 1)
return func(writer http.ResponseWriter, request *http.Request) {
queries := make(map[string][]string, 10)
for key, value := range request.URL.Query() {
queries[key] = value
}
rc := requestContextFromHttpRequest(request, writer, pathParams)
for _, requestListener := range requestListeners {
rc = requestListener(rc)
}
go executeInterrupts(interrupts, rc, interruptChannel)
go func() {
defer catchErrInto(panicChannel)
result := api(rc)
for _, responseListener := range responseListeners {
result = responseListener(result)
}
result.doneAt = time.Now()
successfulResultChannel <- &result
}()
select {
case interrupt := <-interruptChannel:
result := *interrupt
interrupt.complete(request, writer)
for _, apiListener := range apiListeners {
apiListener(rc, result)
}
case success := <-successfulResultChannel:
success.complete(request, writer)
for _, apiListener := range apiListeners {
go apiListener(rc, *success)
}
case err := <-panicChannel:
if recovery == nil {
panic(err)
} else {
status := recovery(rc, err)
write(status, writer)
}
}
}
}
// WatchAPIs is the default request and response logger for stgin.
// It logs the input request and the output response into the console.
func WatchAPIs(request RequestContext, status Status) {
difference := fmt.Sprint(status.doneAt.Sub(request.receivedAt))
if status.StatusCode == http.StatusRequestTimeout {
_ = stginLogger.InfoF("%s -> %s\t\t|%s request timed out after %s%s",
request.Method, request.Url, colored.YELLOW, difference, colored.ResetPrevColor,
)
return
}
statusString := fmt.Sprintf("%v%d%v", getColor(status.StatusCode), status.StatusCode, colored.ResetPrevColor)
_ = stginLogger.InfoF("%s -> %s\t\t| %v | %v", request.Method, request.Url, statusString, difference)
}
type generalFailureMessage struct {
StatusCode int `json:"status_code"`
Path string `json:"path"`
Message string `json:"message"`
Method string `json:"method"`
}
var notFoundDefaultAction API = func(request RequestContext) Status {
return NotFound(Json(&generalFailureMessage{
StatusCode: http.StatusNotFound,
Path: request.Url,
Message: "route not found",
Method: request.Method,
}))
}
var errorAction ErrorHandler = func(request RequestContext, err any) Status {
printStacktrace(fmt.Sprintf("recovering following error: %v%v%v", colored.RED, fmt.Sprint(err), colored.ResetPrevColor))
if parseErr, isParseError := err.(ParseError); isParseError {
return BadRequest(Json(&generalFailureMessage{
StatusCode: 400,
Path: request.Url,
Message: parseErr.Error(),
Method: request.Method,
}))
}
return InternalServerError(Json(&generalFailureMessage{
StatusCode: 500,
Path: request.Url,
Message: "internal server error",
Method: request.Method,
}))
}
type apiHandler struct {
methodWithRoutes map[string][]Route // to optimize request matching time
server *Server
}
func (handler apiHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
var done bool
for _, route := range handler.methodWithRoutes[request.Method] {
accepts, pathParams := route.acceptsAndPathParams(request)
if accepts && acceptsAllQueries(route.expectedQueries, request.URL.Query()) {
requestListeners := append(handler.server.requestListeners, route.controller.requestListeners...)
responseListeners := append(handler.server.responseListeners, route.controller.responseListeners...)
apiListeners := append(handler.server.apiListeners, route.controller.apiListeners...)
interrupts := append(handler.server.interrupts, route.controller.interrupts...)
handlerFunc := translate(
route.Action,
requestListeners,
responseListeners,
apiListeners,
handler.server.errorAction,
pathParams,
interrupts,
)
handlerFunc(writer, request)
done = true
break
}
}
// no route matches the request
if !done {
rc := requestContextFromHttpRequest(request, writer, nil)
status := handler.server.notFoundAction(rc)
statusCode := status.StatusCode
bodyBytes, contentType, marshalErr := marshall(status.Entity)
if marshalErr != nil {
_ = stginLogger.ErrorF(
"could not marshal not found action result:\n\t%v%v%v",
colored.RED, fmt.Sprint(marshalErr), colored.ResetPrevColor,
)
bodyBytes, _ = json.Marshal(&generalFailureMessage{
StatusCode: http.StatusNotFound,
Path: request.URL.Path,
Message: "route not found",
Method: request.Method,
})
statusCode = http.StatusNotFound
contentType = applicationJson
}
writer.Header().Set(contentTypeKey, contentType)
writer.WriteHeader(statusCode)
writer.Write(bodyBytes)
}
}
func routeAppendLog(controllerName, method, path string) string {
return fmt.Sprintf("Adding %v's API:\t%s%v%s\t\t-> %s%v%s",
controllerName,
colored.CYAN, method, colored.ResetPrevColor,
colored.CYAN, path, colored.ResetPrevColor,
)
}
func bindStaticDirLog(routePath string, dir string) string {
return fmt.Sprintf("Binding route :\t%s%s%s\t\tto serve static directory -> %s%s%s",
colored.CYAN, routePath, colored.ResetPrevColor,
colored.GREEN, dir, colored.ResetPrevColor,
)
}
func (server *Server) HttpHandler() http.Handler {
mux := http.NewServeMux()
methodWithRoutes := make(map[string][]Route)
for _, controller := range server.Controllers {
for _, route := range controller.routes {
var log string
if !route.isStaticDir() {
methodWithRoutes[route.Method] = append(methodWithRoutes[route.Method], route)
log = routeAppendLog(controller.Name, route.Method, route.Path)
} else {
dir := route.dir
log = bindStaticDirLog(route.Path, dir)
mux.Handle(route.Path, http.StripPrefix(route.Path, http.FileServer(http.Dir(dir))))
}
_ = stginLogger.Info(log)
}
}
mux.Handle("/", apiHandler{methodWithRoutes: methodWithRoutes, server: server})
return mux
}
// Start executes the server over the specified address.
// In case any uncaught error or panic happens, and is not recovered in the server's error handler,
// the error value is returned as a result.
func (server *Server) Start() error {
_ = stginLogger.InfoF("started server over address: %s%s%s", colored.YELLOW, server.addr, colored.ResetPrevColor)
return http.ListenAndServe(server.addr, server.HttpHandler())
}
// NewServer returns a pointer to a basic stgin Server.
func NewServer(addr string) *Server {
return &Server{
addr: addr,
notFoundAction: notFoundDefaultAction,
errorAction: nil,
Controllers: []*Controller{defaultController},
}
}
// DefaultServer is the recommended approach to get a new Server.
// It includes error handler and api logger by default.
func DefaultServer(addr string) *Server {
server := NewServer(addr)
server.AddAPIListeners(WatchAPIs)
server.errorAction = errorAction
return server
}
func (server *Server) executeInternal(request *http.Request) Status {
var headers http.Header
if request.Header == nil {
headers = emptyHeaders
} else {
headers = request.Header
}
rc := RequestContext{
Url: request.URL.Path,
QueryParams: Queries{request.URL.Query()},
PathParams: PathParams{nil},
Headers: headers,
Body: func() *RequestBody {
return &RequestBody{
underlying: nil,
underlyingBytes: []byte{},
hasFilledBytes: false,
}
},
receivedAt: time.Now(),
Method: request.Method,
ContentLength: request.ContentLength,
Host: request.Host,
MultipartForm: func() *multipart.Form {
return request.MultipartForm
},
Scheme: request.URL.Scheme,
RemoteAddr: request.RemoteAddr,
}
interruptChannel := make(chan *Status, 1)
successfulOperationChannel := make(chan *Status, 1)
// panicChannel should not be defined here, since error handling is on server layer
requestListeners := server.requestListeners
responseListeners := server.responseListeners
apiListeners := server.apiListeners
for _, c := range server.Controllers {
requestListeners = append(requestListeners, c.requestListeners...)
responseListeners = append(responseListeners, c.responseListeners...)
apiListeners = append(apiListeners, c.apiListeners...)
}
for _, modifier := range server.requestListeners {
rc = modifier(rc)
}
for _, interrupt := range server.interrupts {
go interrupt.TriggerFor(rc, interruptChannel)
}
var done bool
go func() {
var result Status
for _, c := range server.Controllers {
if done { break }
for _, route := range c.routes {
matches, pathParams := route.acceptsAndPathParams(request)
if matches && acceptsAllQueries(route.expectedQueries, request.URL.Query()) {
rc.PathParams = PathParams{pathParams}
done = true
result = route.Action(rc)
break
}
}
}
if !done {
result = NotFound(Json(&generalFailureMessage{
StatusCode: 404,
Path: request.URL.Path,
Message: "not found",
Method: request.Method,
}))
}
for _, modifier := range responseListeners {
result = modifier(result)
}
successfulOperationChannel <- &result
}()
select {
case interrupted := <-interruptChannel:
result := *interrupted
for _, watcher := range apiListeners {
go watcher(rc, result)
}
return result
case normal := <-successfulOperationChannel:
result := *normal
for _, watcher := range apiListeners {
go watcher(rc, result)
}
return result
}
}