/
webgo.go
510 lines (429 loc) · 10.3 KB
/
webgo.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
package webgo
import (
"github.com/IntelliQru/config"
"github.com/IntelliQru/logger"
"github.com/IntelliQru/mail"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"time"
"github.com/IntelliQru/i18n"
)
type App struct {
router Router
definitions Definitions
templates *template.Template
staticDir string
workDir string
tmpDir string
langDir string
maxBodyLength int64
defaultLang string
}
const (
CT_JSON = "application/json"
CT_FORM = "application/x-www-form-urlencoded"
CT_MULTIPART = "multipart/form-data"
)
var (
app App
mailSmtpClient *mail.SmtpClient
CFG *config.Config
LOGGER *logger.Logger
)
func init() {
// Init config
{
cfg, err := config.NewConfig()
if err == nil {
err = cfg.ReadConfig()
}
if err != nil {
panic(err.Error())
} else {
CFG = cfg
}
}
// Init logger
{
cp := new(logger.ConsoleProvider)
LOGGER = logger.NewLogger()
LOGGER.RegisterProvider(cp)
LOGGER.AddLogProvider(cp.GetID())
LOGGER.AddErrorProvider(cp.GetID())
LOGGER.AddFatalProvider(cp.GetID())
LOGGER.AddDebugProvider(cp.GetID())
}
// Init application
templates := template.New("template")
filepath.Walk("templates", func(pathToFile string, info os.FileInfo, err error) error {
if path.Ext(pathToFile) == ".html" {
templates.ParseFiles(pathToFile)
}
return nil
})
app = App{}
app.router = Router{}
app.definitions = Definitions{
Handlers: make(map[string][]MiddlewareInterface),
}
app.templates = templates
app.staticDir = "public"
app.defaultLang = "en-US"
if len(CFG.Str("defaultLang")) > 0 {
app.defaultLang = CFG.Str("defaultLang")
}
app.workDir, _ = os.Getwd()
app.langDir = path.Join(app.workDir, "i18n")
app.tmpDir = path.Join(app.workDir, "tmp")
app.maxBodyLength = 131072
_, err := os.Stat(app.tmpDir)
if os.IsNotExist(err) {
err = os.Mkdir(app.tmpDir, os.ModePerm)
if err != nil {
LOGGER.Fatal(err)
}
}
_, err = os.Stat(fmt.Sprint(app.langDir))
if os.IsNotExist(err) {
err = os.Mkdir(app.langDir, os.ModePerm)
if err != nil {
LOGGER.Fatal(err)
}
}
filepath.Walk("i18n", func(pathToFile string, info os.FileInfo, err error) error {
if path.Ext(pathToFile) == ".json" {
err := i18n.LoadTranslationFile(pathToFile)
if err != nil {
LOGGER.Error(err)
}
}
return nil
})
}
func parseRequest(ctx *Context, limit int64) (errorCode int, err error) {
var body []byte
defer func() {
r := recover()
if r != nil {
errorCode = 400
err = errors.New("Bad Request")
}
}()
ctx.Request.Body = http.MaxBytesReader(ctx.Response, ctx.Request.Body, limit)
err = ctx.Request.ParseForm()
if err != nil {
errorCode = 400
return
}
// Копируем данные
for i := range ctx.Request.Form {
ctx.Query[i] = ctx.Request.Form[i]
}
switch ctx.ContentType {
case CT_JSON:
defer ctx.Request.Body.Close()
body, err = ioutil.ReadAll(ctx.Request.Body)
if err != nil {
errorCode = 400
return
}
var data interface{}
err = json.Unmarshal(body, &data)
if err != nil {
errorCode = 400
return
}
ctx._Body = body
ctx.Body = data.(map[string]interface{})
return
case CT_FORM:
err = ctx.Request.ParseForm()
if err != nil {
errorCode = 400
return
}
ctx._Body = []byte(ctx.Request.Form.Encode())
case CT_MULTIPART:
err = ctx.Request.ParseMultipartForm(limit)
if err != nil {
//TODO: 400 or 413
errorCode = 400
return
}
for _, fheaders := range ctx.Request.MultipartForm.File {
for _, hdr := range fheaders {
var infile multipart.File
if infile, err = hdr.Open(); nil != err {
LOGGER.Error(err)
errorCode = 500
return
}
var outfile *os.File
if outfile, err = ioutil.TempFile(app.tmpDir, "tmp_"); err != nil {
LOGGER.Error(err)
errorCode = 500
return
}
// 32K buffer copy
var written int64
if written, err = io.Copy(outfile, infile); nil != err {
LOGGER.Error(err)
errorCode = 500
return
}
tmpFile := File{
Path: outfile.Name(),
Name: hdr.Filename,
Size: int64(written),
}
ctx.Files = append(ctx.Files, tmpFile)
}
}
default:
if ctx.Request.ContentLength > 0 {
err = errors.New("Bad Request")
errorCode = 400
}
return
}
for i := range ctx.Request.Form {
ctx.Body[i] = ctx.Request.Form[i]
}
return
}
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//cn, ok := w.(http.CloseNotifier)
//if !ok {
// LOGGER.Fatal("don't support CloseNotifier")
//}
var vc reflect.Value
var Action reflect.Value
method := r.Method
path := r.URL.Path
if len(path) > 1 && strings.HasSuffix(path, "/") {
http.Redirect(w, r, path[:len(path)-1], 301)
return
}
// TODO как отдавать статику?
/*// Отдаем статику если был запрошен файл
ext := filepath.Ext(path)
if ext != "" {
http.ServeFile(w, r, app.staticDir+filepath.Clean(path))
return
}*/
route := a.router.Match(method, path)
if route == nil {
http.Error(w, "", 404)
return
}
if route.Options.Timeout == 0 {
route.Options.Timeout = 2
}
//timeout := time.After(route.Options.Timeout * time.Second)
//done := make(chan bool)
vc = reflect.New(route.ControllerType)
Action = vc.MethodByName(route.Options.Action)
var err error
ctx := Context{
Action: route.Options.Action,
Response: w,
Request: r,
Query: make(map[string]interface{}),
Body: make(map[string]interface{}),
Params: route.Params,
Method: method,
Lang: app.defaultLang,
}
ctx.ContentType = ctx.Request.Header.Get("Content-Type")
ctx.ContentType, _, err = mime.ParseMediaType(ctx.ContentType)
if ctx.Request.ContentLength > 0 && err != nil {
http.Error(w, "", 400)
return
}
// Определение языка
if route.Options.I18n {
acceptLang := ctx.Request.Header.Get("Accept-Language")
cookieLang := ctx.GetCookie("lang")
if len(cookieLang) != 0 && i18n.CheckLang(cookieLang) {
ctx.Lang = cookieLang
} else {
// Находим поддерживаемый язык из Accept-Language
start := 0
for end, chr := range acceptLang {
switch chr {
case ',', ';':
tag := strings.TrimSpace(acceptLang[start:end])
if i18n.CheckLang(tag) {
ctx.Lang = tag
break
}
start = end + 1
}
}
}
}
Controller, ok := vc.Interface().(ControllerInterface)
if !ok {
LOGGER.Error(errors.New("controller is not ControllerInterface"))
http.Error(w, "", 500)
return
}
// Парсим запрос
var maxBodyLength int64 = app.maxBodyLength
if route.Options.BodyLength > 0 {
maxBodyLength = route.Options.BodyLength
}
code, err := parseRequest(&ctx, maxBodyLength)
if err != nil {
http.Error(w, "", code)
return
}
// Инициализация контекста
Controller.Init(&ctx)
// Запуск предобработчика
if !Controller.Prepare() {
Controller.exec()
return
}
// Запуск цепочки middleware
if !app.definitions.Run(route.Options.MiddlewareGroup, &ctx) {
return
}
in := make([]reflect.Value, 0)
Action.Call(in)
//go func () {
// in := make([]reflect.Value, 0)
// Action.Call(in)
// done <- true
//}()
// Запуск постобработчика
Controller.Finish()
if ctx.ContentType == "multipart/form-data" {
err = ctx.Files.RemoveAll()
if err != nil {
LOGGER.Error(err)
}
err = ctx.Request.MultipartForm.RemoveAll()
if err != nil {
LOGGER.Error(err)
}
}
if strings.ToLower(r.Header.Get("Upgrade")) != "websocket" {
Controller.exec()
}
}
func RegisterMiddleware(name string, plugins ...MiddlewareInterface) {
for _, plugin := range plugins {
app.definitions.Register(name, plugin)
}
}
func (a *App) Get(url string, opts RouteOptions) {
a.addRoute(http.MethodGet, url, &opts)
}
func (a *App) Post(url string, opts RouteOptions) {
a.addRoute(http.MethodPost, url, &opts)
}
func (a *App) Put(url string, opts RouteOptions) {
a.addRoute(http.MethodPut, url, &opts)
}
func (a *App) Delete(url string, opts RouteOptions) {
a.addRoute(http.MethodDelete, url, &opts)
}
func (a *App) Options(url string, opts RouteOptions) {
a.addRoute(http.MethodOptions, url, &opts)
}
func (a *App) addRoute(method, url string, opts *RouteOptions) {
err := a.router.Add(method, url, opts)
if err != nil {
LOGGER.Fatal(err)
}
}
func (a *App) AddRouting(r *Router) error {
return r.Copy(&a.router)
}
func AddRouting(r *Router) error {
return app.AddRouting(r)
}
func Get(url string, opts RouteOptions) {
app.Get(url, opts)
}
func Post(url string, opts RouteOptions) {
app.Post(url, opts)
}
func Put(url string, opts RouteOptions) {
app.Put(url, opts)
}
func Delete(url string, opts RouteOptions) {
app.Delete(url, opts)
}
func Options(url string, opts RouteOptions) {
app.Options(url, opts)
}
func Tfunc(lang string) i18n.TFuncHandler {
return i18n.Tfunc(lang)
}
func Mail(address string, subject string, tpl string, model interface{}) (err error) {
if mailSmtpClient == nil {
mailSmtpClient = &mail.SmtpClient{
Host: CFG.Str("smtp_host"),
Port: CFG.Str("smtp_port"),
User: CFG.Str("smtp_user"),
Password: CFG.Str("smtp_passwd"),
From: CFG.Str("smtp_from"),
}
if len(mailSmtpClient.Host) == 0 {
err = errors.New("Failed smpt client settings. The mail can't be sent.")
return
}
}
buffer := bytes.NewBufferString("")
err = app.templates.ExecuteTemplate(buffer, tpl+".html", model)
if err != nil {
return
}
message := mail.NewMessage(mailSmtpClient, address, subject, buffer.String())
err = message.SendMail()
if err != nil {
return
}
return
}
func Run() {
var r *int = flag.Int("r", 0, "read timeout")
var w *int = flag.Int("w", 0, "write timeout")
port := CFG.Int("port")
if port == 0 {
port = 80
}
host := CFG.Str("host")
if host == "" {
host = "127.0.0.1"
}
address := fmt.Sprintf("%s:%d", host, port)
LOGGER.Log("WebGO running", address)
server := http.Server{
Addr: address,
ReadTimeout: time.Duration(*r) * time.Second,
WriteTimeout: time.Duration(*w) * time.Second,
Handler: &app,
}
//server.SetKeepAlivesEnabled(false)
err := server.ListenAndServe()
if err != nil {
LOGGER.Fatal(err)
}
}