-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
333 lines (296 loc) · 10.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
package stgin
import (
"encoding/json"
"fmt"
"github.com/AminMal/slogger/colored"
"net/http"
"time"
)
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
timeout time.Duration
}
// 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": handler.AllowOrigin,
"Access-Control-Allow-Credentials": handler.AllowCredentials,
"Access-Control-Allow-Headers": handler.AllowHeaders,
"Access-Control-Allow-Methods": 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
}
func (server *Server) SetTimeout(dur time.Duration) {
server.timeout = dur
}
func catchTime(timeout time.Duration, timeoutChan chan struct{}) {
if timeout > 0 {
<-time.After(timeout)
timeoutChan <- struct{}{}
}
}
// 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,
timeout time.Duration,
) http.HandlerFunc {
panicChannel := make(chan interface{}, 1)
successfulResultChannel := make(chan *Status, 1)
timeoutChannel := make(chan struct{}, 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 catchTime(timeout, timeoutChannel)
go func() {
defer func() {
if err := recover(); err != nil {
panicChannel <- err
}
return
}()
result := api(rc)
for _, responseListener := range responseListeners {
result = responseListener(result)
}
result.doneAt = time.Now()
successfulResultChannel <- &result
}()
select {
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)
}
case <-timeoutChannel:
result := contextTimeoutResponse()
result.complete(request, writer)
for _, apiListener := range apiListeners {
go apiListener(rc, result)
}
}
}
}
// 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,
)
}
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,
}))
}
func contextTimeoutResponse() Status {
return Status{
StatusCode: http.StatusRequestTimeout,
Entity: Text("request timed out"),
doneAt: time.Now(),
}
}
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...)
handlerFunc := translate(
route.Action,
requestListeners,
responseListeners,
apiListeners,
handler.server.errorAction,
pathParams,
handler.server.timeout,
)
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) handler() 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.handler())
}
// 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},
timeout: -time.Millisecond,
}
}
// 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
}