-
Notifications
You must be signed in to change notification settings - Fork 0
/
just.go
390 lines (344 loc) · 10.6 KB
/
just.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
package just
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"runtime/debug"
"strconv"
"strings"
"sync"
)
const (
Version = "v0.1.18"
DebugEnvName = "JUST_DEBUG_MODE"
)
// Debug mode.
var (
debugMutex = sync.RWMutex{}
debugMode = true
)
// Errors
var (
ErrInvalidContext = errors.New("invalid context")
ErrRecoverInvalidResponse = errors.New("invalid response, recover panic")
)
// JUST Application interface.
type IApplication interface {
IRouter
Profiler() IProfiler
Translator() ITranslator
SerializerManager() ISerializerManager
TemplatingManager() ITemplatingManager
LocalDo(req *http.Request) IResponse
SetProfiler(p IProfiler) IApplication
SetTranslator(t ITranslator) IApplication
SetNoRouteHandler(handler HandlerFunc) IApplication
SetNoImplementedHandler(handler HandlerFunc) IApplication
ServeHTTP(w http.ResponseWriter, req *http.Request)
Run(address string) error
RunTLS(address, certFile, keyFile string) error
}
type application struct {
Router
pool sync.Pool
// Стандартные обработчики ошибок
noRouteHandler HandlerFunc
noImplementedHandler HandlerFunc
// Менеджер сериализаторов с поддержкой многопоточности
serializerManager serializerManager
// Менеджер для работы с шаблонами
templatingManager templatingManager
// Транлятор локализации i18n
translator ITranslator
// Менеджер профилирования
profiler IProfiler
}
func (app *application) printWelcomeMessage(address string, tls bool) {
fmt.Print("[WELCOME] Just Web Framework ", Version)
if tls {
fmt.Println(" [RUN ON", address, "/ TLS]")
} else {
fmt.Println(" [RUN ON", address+"]")
}
}
func (app *application) Translator() ITranslator {
return app.translator
}
func (app *application) Profiler() IProfiler {
return app.profiler
}
func (app *application) TemplatingManager() ITemplatingManager {
return &app.templatingManager
}
func (app *application) SetProfiler(p IProfiler) IApplication {
app.profiler = p
return app
}
func (app *application) SetTranslator(t ITranslator) IApplication {
app.translator = t
return app
}
func (app *application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Усли поступил несуществующий запрос - выходим
if req == nil || w == nil {
return
}
// Берем контекст из пула
c := app.pool.Get().(*Context).reset()
c.Request, c.IsFrozenRequestBody = req, true
// Передаем контекст в обработчик запросов для заполнения ответа
app.handleHttpRequest(w, c)
// Складываем контекст в пул
app.pool.Put(c)
}
func (app *application) checkMethodForHaveBody(method string) bool {
return method == "POST" || method == "PATCH" || method == "PUT"
}
func (app *application) handleHttpRequest(w http.ResponseWriter, c *Context) {
if !c.IsValid() {
if app.profiler != nil {
app.profiler.Warning(ErrInvalidContext)
}
return
}
httpMethod, path := c.Request.Method, c.Request.URL.Path
if app.checkMethodForHaveBody(httpMethod) && c.Request.Body != nil {
// Преобразовываем данные
if b, _ := ioutil.ReadAll(c.Request.Body); len(b) > 0 {
c.Request.Body.Close()
// Новое тело запроса с возможностью сбрасывания позиции чтения
c.Request.Body = ioutil.NopCloser(bytes.NewReader(b))
}
}
if app.profiler != nil {
// Фиксация начала обработки запроса
app.profiler.OnStartRequest(c.Request)
// Профилирование выходных данных
w = &profiledResponseWriter{
profiler: app.profiler,
writer: w,
}
}
// Recover
defer func() {
if rvr := recover(); rvr != nil {
fmt.Fprintf(os.Stderr, "Panic: %+v\n", rvr)
debug.PrintStack()
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
if app.profiler != nil {
app.profiler.Error(ErrRecoverInvalidResponse)
}
}
}()
// Выполняем handlers из роутеров
response, existRoute := app.handleRouter(&app.Router, httpMethod, path, c)
// Если ответ пустой
if response == nil {
// Если ответа так и нет, но был найден роут -> выдаем ошибку пустого ответа
if existRoute {
// 501 ошибка
response = app.noImplementedHandler(c)
} else {
// Если ничего так и нет, выводим 404 ошибку
// но перед этим прогоняем все обработчики
if response = c.resetRoute(app, nil).Next(); response == nil {
response = app.noRouteHandler(c)
}
}
}
if app.profiler != nil {
// Фиксация выбора роута
app.profiler.OnSelectRoute(c.Request, c.routeInfo)
}
// Отправляем response клиенту
if response != nil {
if streamFunc, ok := response.GetStreamHandler(); ok {
streamFunc(w, c.Request)
} else {
if response.HasHeaders() {
// Обработка заголовков
headers, hasRedirect, hasServeFiles := response.GetHeaders(), false, false
for key, value := range headers {
if key == StrongRedirectHeaderKey {
hasRedirect = true
continue
} else if key == ServeFileHeaderKey {
hasServeFiles = true
continue
}
w.Header().Set(key, value)
}
if hasRedirect {
http.Redirect(w, c.Request, headers[StrongRedirectHeaderKey], response.GetStatus())
return
} else if hasServeFiles {
http.ServeFile(w, c.Request, headers[ServeFileHeaderKey])
return
}
}
w.WriteHeader(response.GetStatus())
w.Write(response.GetData())
}
return
}
// Если ничего не смогли сделать, выдаем 405 ошибку
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
if app.profiler != nil {
app.profiler.Error(http.ErrNotSupported)
}
}
// Локальный вызов запроса внутри движка
func (app *application) LocalDo(req *http.Request) IResponse {
if req == nil {
return nil
}
c := app.pool.Get().(*Context).reset()
defer app.pool.Put(c)
c.Request, c.IsFrozenRequestBody = req, true
c.isLocalRequest = true
httpMethod, path := c.Request.Method, c.Request.URL.Path
if app.checkMethodForHaveBody(httpMethod) && c.Request.Body != nil {
if b, _ := ioutil.ReadAll(c.Request.Body); len(b) > 0 {
c.Request.Body.Close()
c.Request.Body = ioutil.NopCloser(bytes.NewReader(b))
}
}
defer func() {
if rvr := recover(); rvr != nil {
fmt.Fprintf(os.Stderr, "Panic: %+v\n", rvr)
debug.PrintStack()
}
}()
response, _ := app.handleRouter(&app.Router, httpMethod, path, c)
return response
}
func (app *application) handleRouter(router *Router, httpMethod, path string, c *Context) (IResponse, bool) {
if router != nil {
// Поиск роута
if router.routes != nil && len(router.routes) > 0 {
if routes, ok := router.routes[httpMethod]; ok && len(routes) > 0 {
for _, route := range routes {
if params, ok := route.CheckPath(path); ok {
return c.resetRoute(route, params).nextHandler()
}
}
}
}
// Поиск следующего роутера
if router.groups != nil && len(router.groups) > 0 {
for _, r := range router.groups {
if strings.LastIndexByte(r.basePath, '}') >= 0 && r.rxPath != nil {
if _, ok := r.CheckPath(path); ok {
return app.handleRouter(r, httpMethod, path, c)
}
continue
}
if strings.Index(path, r.basePath) >= 0 {
return app.handleRouter(r, httpMethod, path, c)
}
}
}
}
return nil, false
}
func (app *application) Run(address string) error {
app.printWelcomeMessage(address, false)
return http.ListenAndServe(address, app)
}
func (app *application) RunTLS(address, certFile, keyFile string) error {
app.printWelcomeMessage(address, true)
return http.ListenAndServeTLS(address, certFile, keyFile, app)
}
func (app *application) SerializerManager() ISerializerManager {
return &app.serializerManager
}
func (app *application) SetNoRouteHandler(handler HandlerFunc) IApplication {
app.noRouteHandler = handler
return app
}
func (app *application) SetNoImplementedHandler(handler HandlerFunc) IApplication {
app.noImplementedHandler = handler
return app
}
func noRouteDefHandler(c *Context) IResponse {
return c.Serializer().Response(404,
NewError("404", c.Trans("Route not found")).SetMetadata(H{
"method": c.Request.Method,
"path": c.Request.URL.Path,
}))
}
func noImplementedDefHandler(c *Context) IResponse {
meta := H{
"method": c.Request.Method,
"path": c.Request.URL.Path,
}
if c.routeInfo != nil {
meta["route"] = c.routeInfo.BasePath()
}
return c.Serializer().Response(501,
NewError("501", c.Trans("Response not implemented for current Route")).SetMetadata(meta))
}
func (app *application) initPool() *application {
app.pool.New = func() interface{} {
return &Context{app: app}
}
return app
}
// Set default serializer to just application (json, xml, form-data, x-www-form-urlencoded)
func SetDefSerializers(app IApplication) IApplication {
app.SerializerManager().SetSerializer("json", []string{
"application/json",
}, &JsonSerializer{Ch: "utf-8"}).SetSerializer("xml", []string{
"text/xml",
"application/xml",
}, &XmlSerializer{Ch: "utf-8"}).SetSerializer("form", []string{
"multipart/form-data",
"application/x-www-form-urlencoded",
}, &FormSerializer{Ch: "utf-8", OnlyDeserialize: true}).SetDefaultName("json")
return app
}
// Set default renderers (HTML UTF-8)
func SetDefRenderers(app IApplication) IApplication {
app.TemplatingManager().SetRenderer("html", &HTMLRenderer{Charset: "utf-8"})
return app
}
// Create new clear JUST application.
// Without serializers and renderers.
func NewClear() IApplication {
app := &application{
Router: Router{
basePath: "/",
handlers: nil,
routeParamNames: nil,
groups: nil,
routes: nil,
},
noRouteHandler: noRouteDefHandler,
noImplementedHandler: noImplementedDefHandler,
translator: &baseTranslator{defaultLocale: "en"},
}
return app.initPool()
}
// Create new default JUST application.
func New() IApplication {
return SetDefSerializers(SetDefRenderers(NewClear()))
}
// Change debug mode
func SetDebugMode(value bool) {
debugMutex.RLock()
defer debugMutex.RUnlock()
debugMode = value
}
func IsDebug() bool {
debugMutex.Lock()
defer debugMutex.Unlock()
return debugMode
}
func init() {
if value, err := strconv.ParseBool(os.Getenv(DebugEnvName)); err == nil {
SetDebugMode(value)
}
}