This repository has been archived by the owner on Jun 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
1239 lines (1140 loc) · 31.9 KB
/
app.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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package xweb
import (
"errors"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/coscms/tagfast"
"github.com/coscms/xweb/httpsession"
"github.com/coscms/xweb/lib/route"
"github.com/coscms/xweb/log"
)
var (
mapperType = reflect.TypeOf(Mapper{})
)
type JSON struct {
Data interface{}
}
type JSONP struct {
Data interface{}
Callback string
}
type SHOW struct {
Tmpl string
*T
}
type JUMP struct {
Url string
Code int
}
type XML struct {
Data interface{}
}
type FILE struct {
Data string
}
var ExtensionValidator = make(map[string]func(*App, http.ResponseWriter, *http.Request) bool)
const (
Debug = iota + 1
Product
XSRF_TAG string = "_xsrf"
)
type App struct {
BasePath string
Name string
Domain string
Route *route.Route
filters []Filter
Server *Server
AppConfig *AppConfig
Config *CONF
Actions map[string]interface{}
ActionsPath map[reflect.Type]string
ActionsNamePath map[string]string
ActionsMethodRoute map[string]map[string]string
FuncMaps template.FuncMap
Logger *log.Logger
VarMaps T
SessionManager *httpsession.Manager //Session manager
RootTemplate *template.Template
ErrorTemplate *template.Template
StaticVerMgr *StaticVerMgr
TemplateMgr *TemplateMgr
ContentEncoding string
RequestTime time.Time
Cryptor
XsrfManager
}
func NewAppConfig() *AppConfig {
return &AppConfig{
Mode: Product,
StaticDir: "static",
TemplateDir: "templates",
SessionOn: true,
SessionTimeout: 3600,
MaxUploadSize: 10 * 1024 * 1024,
StaticFileVersion: true,
CacheTemplates: true,
ReloadTemplates: true,
CheckXsrf: true,
FormMapToStruct: true,
StaticFileParser: make(map[string]func(string, *http.Request, http.ResponseWriter) (bool, int64)),
}
}
type AppConfig struct {
Mode int
StaticDir string
TemplateDir string
SessionOn bool
MaxUploadSize int64
CookieSecret string
CookieLimitIP bool
CookieLimitUA bool
CookiePrefix string
CookieDomain string
StaticFileVersion bool
CacheTemplates bool
ReloadTemplates bool
CheckXsrf bool
SessionTimeout time.Duration
FormMapToStruct bool
EnableHttpCache bool
AuthBasedOnCookie bool
StaticFileParser map[string]func(string, *http.Request, http.ResponseWriter) (bool, int64)
//example: StaticFileParser[php]=func(fileName string, req *http.Request, w http.ResponseWriter)(bool, int64){...}
}
func NewApp(path string, name string) *App {
return &App{
BasePath: path,
Name: name,
Route: route.NewRoute(),
AppConfig: NewAppConfig(),
Config: NewCONF(),
Actions: map[string]interface{}{},
ActionsPath: map[reflect.Type]string{},
ActionsNamePath: map[string]string{},
ActionsMethodRoute: make(map[string]map[string]string),
FuncMaps: DefaultFuncs,
VarMaps: T{},
filters: make([]Filter, 0),
StaticVerMgr: DefaultStaticVerMgr,
TemplateMgr: DefaultTemplateMgr,
Cryptor: DefaultCryptor,
XsrfManager: DefaultXsrfManager,
}
}
func (a *App) IsRootApp() bool {
return a.BasePath == "/"
}
func (a *App) initApp() {
var isRootApp bool = a.IsRootApp()
if a.AppConfig.StaticFileVersion {
if isRootApp || a.Server.RootApp.AppConfig.StaticDir != a.AppConfig.StaticDir {
if !isRootApp {
a.StaticVerMgr = new(StaticVerMgr)
}
a.StaticVerMgr.Init(a, a.AppConfig.StaticDir)
} else {
a.StaticVerMgr = a.Server.RootApp.StaticVerMgr
}
}
if a.AppConfig.CacheTemplates {
if isRootApp || a.Server.RootApp.AppConfig.TemplateDir != a.AppConfig.TemplateDir {
if !isRootApp {
a.TemplateMgr = new(TemplateMgr)
}
a.TemplateMgr.Init(a, a.AppConfig.TemplateDir, a.AppConfig.ReloadTemplates)
} else {
a.TemplateMgr = a.Server.RootApp.TemplateMgr
}
}
a.FuncMaps["StaticUrl"] = a.StaticUrl
a.FuncMaps["XsrfName"] = XsrfName
a.VarMaps["XwebVer"] = Version
if a.AppConfig.SessionOn {
if a.Server.SessionManager != nil {
a.SessionManager = a.Server.SessionManager
} else {
a.SessionManager = httpsession.Default()
if a.AppConfig.SessionTimeout > time.Second {
a.SessionManager.SetMaxAge(a.AppConfig.SessionTimeout)
}
a.SessionManager.Run()
}
}
if a.Logger == nil {
a.Logger = a.Server.Logger
}
}
func (a *App) Close() {
if a.AppConfig.StaticFileVersion && a.StaticVerMgr != nil {
a.StaticVerMgr.Close()
}
if a.AppConfig.CacheTemplates && a.TemplateMgr != nil {
a.TemplateMgr.Close()
}
if a.AppConfig.SessionOn && a.Server.SessionManager == nil &&
a.SessionManager != nil {
//a.SessionManager.Close()
}
}
func (a *App) DelDomain() {
a.Domain = ""
if domain, ok := a.Server.App2Domain[a.Name]; ok {
delete(a.Server.App2Domain, a.Name)
delete(a.Server.Domain2App, domain)
}
}
func (a *App) SetDomain(domain string) {
a.Domain = domain
a.Server.App2Domain[a.Name] = domain
a.Server.Domain2App[domain] = a.Name
}
func (a *App) SetStaticDir(dir string) {
a.AppConfig.StaticDir = dir
}
func (a *App) SetTemplateDir(path string) {
a.AppConfig.TemplateDir = path
}
func (a *App) getTemplatePath(name string) string {
templateFile := path.Join(a.AppConfig.TemplateDir, name)
if fileExists(templateFile) {
return templateFile
}
return ""
}
func (app *App) SetConfig(name string, val interface{}) {
app.Config.SetInterface(name, val)
}
func (app *App) GetConfig(name string) interface{} {
return app.Config.GetInterface(name)
}
func (app *App) SetConfigString(name string, val string) {
app.Config.SetString(name, val)
}
func (app *App) GetConfigString(name string) string {
return app.Config.GetString(name)
}
func (app *App) AddAction(cs ...interface{}) {
for _, c := range cs {
app.AddRouter("/", c)
}
}
func (app *App) AutoAction(cs ...interface{}) {
for _, c := range cs {
t := reflect.Indirect(reflect.ValueOf(c)).Type()
name := t.Name()
if strings.HasSuffix(name, "Action") {
path := strings.ToLower(name[:len(name)-6])
app.AddRouter("/"+path, c)
} else {
app.Warn("AutoAction needs a named ends with Action")
}
}
}
func (app *App) Assign(name string, varOrFun interface{}) {
if reflect.TypeOf(varOrFun).Kind() == reflect.Func {
app.FuncMaps[name] = varOrFun
} else {
app.VarMaps[name] = varOrFun
}
}
func (app *App) MultiAssign(t *T) {
for name, value := range *t {
app.Assign(name, value)
}
}
func (app *App) AddFilter(filter Filter) {
app.filters = append(app.filters, filter)
}
func (app *App) Debug(params ...interface{}) {
args := append([]interface{}{"[" + app.Name + "]"}, params...)
app.Logger.Debug(args...)
}
func (app *App) Info(params ...interface{}) {
args := append([]interface{}{"[" + app.Name + "]"}, params...)
app.Logger.Info(args...)
}
func (app *App) Warn(params ...interface{}) {
args := append([]interface{}{"[" + app.Name + "]"}, params...)
app.Logger.Warn(args...)
}
func (app *App) Error(params ...interface{}) {
args := append([]interface{}{"[" + app.Name + "]"}, params...)
app.Logger.Error(args...)
}
func (app *App) Fatal(params ...interface{}) {
args := append([]interface{}{"[" + app.Name + "]"}, params...)
app.Logger.Fatal(args...)
}
func (app *App) Panic(params ...interface{}) {
args := append([]interface{}{"[" + app.Name + "]"}, params...)
app.Logger.Panic(args...)
}
func (app *App) Debugf(format string, params ...interface{}) {
app.Logger.Debugf("["+app.Name+"] "+format, params...)
}
func (app *App) Infof(format string, params ...interface{}) {
app.Logger.Infof("["+app.Name+"] "+format, params...)
}
func (app *App) Warnf(format string, params ...interface{}) {
app.Logger.Warnf("["+app.Name+"] "+format, params...)
}
func (app *App) Errorf(format string, params ...interface{}) {
app.Logger.Errorf("["+app.Name+"] "+format, params...)
}
func (app *App) Fatalf(format string, params ...interface{}) {
app.Logger.Fatalf("["+app.Name+"] "+format, params...)
}
func (app *App) Panicf(format string, params ...interface{}) {
app.Logger.Panicf("["+app.Name+"] "+format, params...)
}
func (app *App) filter(w http.ResponseWriter, req *http.Request) bool {
for _, filter := range app.filters {
if !filter.Do(w, req) {
return false
}
}
return true
}
func (app *App) AddRouter(url string, c interface{}) {
t := reflect.TypeOf(c).Elem()
v := reflect.ValueOf(c)
actionFullName := t.Name()
actionShortName := strings.TrimSuffix(actionFullName, "Action")
actionShortName = strings.ToLower(actionShortName)
app.ActionsPath[t] = url
app.Actions[actionFullName] = c
app.ActionsNamePath[actionFullName] = url
app.ActionsMethodRoute[actionFullName] = make(map[string]string)
for i := 0; i < t.NumField(); i++ {
if t.Field(i).Type != mapperType {
continue
}
name := t.Field(i).Name
a := strings.Title(name)
m := v.MethodByName(a)
if !m.IsValid() {
continue
}
tag := t.Field(i).Tag
tagStr := tag.Get("xweb")
methods := map[string]bool{} //map[string]bool{"GET": true, "POST": true}
extensions := map[string]bool{} //map[string]bool{"HTML": true, "JSON": true}
group := map[string]bool{} //map[string]bool{"GET_HTML": true, "POST_JSON": true}
var p, meStr string
if tagStr != "" {
tags := strings.Split(tagStr, " ")
path := tagStr
length := len(tags)
if length >= 2 { //`xweb:"GET|POST /index"`
meStr = tags[0]
path = tags[1]
if path == "" {
path = name
}
if tags[1][0] != '/' {
path = "/" + actionShortName + "/" + path
}
} else if length == 1 {
if matched, _ := regexp.MatchString(`^[A-Z.]+(\|[A-Z]+)*$`, tags[0]); !matched {
//非全大写字母时,判断为网址规则
path = tags[0]
if tags[0][0] != '/' { //`xweb:"index"`
path = "/" + actionShortName + "/" + path
}
} else { //`xweb:"GET|POST"`
meStr = tags[0]
path = "/" + actionShortName + "/" + name
}
} else {
path = "/" + actionShortName + "/" + name
}
p = strings.TrimRight(url, "/") + path
} else {
p = strings.TrimRight(url, "/") + "/" + actionShortName + "/" + name
}
p = removeStick(p)
methodsStr := ""
extensionsStr := ""
if meStr != "" {
me := strings.Split(meStr, ".")
methodsStr = me[0]
if len(me) > 1 {
extensionsStr = me[1]
}
}
if methodsStr != "" {
for _, method := range strings.Split(methodsStr, "|") {
method = strings.ToUpper(method)
m := v.MethodByName(a + "_" + method)
methods[method] = m.IsValid()
}
} else {
m := v.MethodByName(a + "_GET")
methods["GET"] = m.IsValid()
m = v.MethodByName(a + "_POST")
methods["POST"] = m.IsValid()
}
if extensionsStr != "" {
for _, extension := range strings.Split(extensionsStr, "|") {
extension = strings.ToUpper(extension)
m := v.MethodByName(a + "_" + extension)
extensions[extension] = m.IsValid()
}
}
if len(methods) > 0 && len(extensions) > 0 {
for method, _ := range methods {
for extension, _ := range extensions {
key := method + "_" + extension
m := v.MethodByName(a + "_" + key)
group[key] = m.IsValid()
}
}
}
app.Route.Set(p, a, methods, extensions, group, t)
app.Debug("Action:", actionFullName+"."+a+";", "Route Information:", p+";", "Request Method:", methods)
}
}
func (a *App) ElapsedTimeString() string {
return fmt.Sprintf("%.3fs", a.ElapsedTime())
}
func (a *App) ElapsedTime() float64 {
return time.Now().Sub(a.RequestTime).Seconds()
}
func (a *App) VisitedLog(req *http.Request, statusCode int, requestPath string, responseSize int64) {
if statusCode == 0 {
statusCode = 200
}
if statusCode >= 200 && statusCode < 400 {
a.Info(req.RemoteAddr, req.Method, statusCode, requestPath, responseSize, a.ElapsedTimeString())
} else {
a.Error(req.RemoteAddr, req.Method, statusCode, requestPath, responseSize, a.ElapsedTimeString())
}
}
// the main route handler in web.go
func (a *App) routeHandler(req *http.Request, w http.ResponseWriter) {
var (
requestPath string = req.URL.Path
statusCode int = 0
responseSize int64 = 0
)
defer func() {
a.VisitedLog(req, statusCode, requestPath, responseSize)
}()
if !a.IsRootApp() || a.Server.Config.UrlSuffix != "" || a.Server.Config.UrlPrefix != "" {
// static files, needed op
if req.Method == "GET" || req.Method == "HEAD" {
success, size := a.TryServingFile(requestPath, req, w)
if success {
statusCode = 200
responseSize = size
return
}
if requestPath == "/favicon.ico" {
statusCode = 404
a.error(w, 404, "Page not found")
return
}
}
}
//ignore errors from ParseForm because it's usually harmless.
ct := req.Header.Get("Content-Type")
if strings.Contains(ct, "multipart/form-data") {
req.ParseMultipartForm(a.AppConfig.MaxUploadSize)
if len(req.PostForm) == 0 {
req.PostForm = req.MultipartForm.Value
}
} else {
req.ParseForm()
}
//Set the default content-type
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if !a.filter(w, req) {
statusCode = 302
return
}
extension := "html"
reqExtension := "HTML"
if epos := strings.LastIndex(req.URL.Path, "."); epos > 0 && epos+1 < len(req.URL.Path) {
extension = req.URL.Path[epos+1:]
req.URL.Path = req.URL.Path[0:epos]
reqExtension = strings.ToUpper(extension)
}
if fn, ok := ExtensionValidator[extension]; ok {
if !fn(a, w, req) {
return
}
}
requestPath = req.URL.Path //支持filter更改req.URL.Path
reqPath := removeStick(requestPath)
if a.Domain == "" && a.BasePath != "/" {
reqPath = "/" + strings.TrimPrefix(reqPath, a.BasePath)
}
reqMethod := Ternary(req.Method == "HEAD", "GET", req.Method).(string)
args, fnName, rfType, onMethod, onExtension, onGroup := a.Route.Get(reqPath, reqMethod, reqExtension)
if rfType != nil && fnName != "" {
var (
isBreak bool
suffix string
)
if onGroup {
suffix = "_" + reqMethod + "_" + reqExtension
} else if onMethod {
suffix = "_" + reqMethod
} else if onExtension {
suffix = "_" + reqExtension
}
isBreak, statusCode, responseSize = a.run(req, w, fnName, rfType, args, suffix, extension)
if isBreak {
return
}
}
// try serving index.html or index.htm
if req.Method == "GET" || req.Method == "HEAD" {
if ok, size := a.TryServingFile(path.Join(requestPath, "index.html"), req, w); ok {
statusCode = 200
responseSize = size
return
} else if ok, size := a.TryServingFile(path.Join(requestPath, "index.htm"), req, w); ok {
statusCode = 200
responseSize = size
return
}
}
a.error(w, 404, "Page not found")
statusCode = 404
}
func (a *App) run(req *http.Request, w http.ResponseWriter,
handlerName string, reflectType reflect.Type,
args []reflect.Value, handlerSuffix string, extensionName string) (isBreak bool,
statusCode int, responseSize int64) {
if handlerSuffix != "" {
handlerName += handlerSuffix
}
isBreak = true
vc := reflect.New(reflectType)
c := &Action{
Request: req,
App: a,
ResponseWriter: w,
T: T{},
f: T{},
Option: &ActionOption{
AutoMapForm: a.AppConfig.FormMapToStruct,
CheckXsrf: a.AppConfig.CheckXsrf,
},
ExtensionName: extensionName,
args: make([]string, len(args)),
}
for k, v := range args {
c.args[k] = v.String()
}
for k, v := range a.VarMaps {
c.T[k] = v
}
elem := vc.Elem()
//设置Action字段的值
fieldA := elem.FieldByName("Action")
if fieldA.IsValid() {
fieldA.Set(reflect.ValueOf(c))
}
//设置C字段的值
fieldC := elem.FieldByName("C")
if fieldC.IsValid() {
fieldC.Set(reflect.ValueOf(vc))
}
//执行Init方法
initM := vc.MethodByName("Init")
if initM.IsValid() {
initM.Call([]reflect.Value{})
}
if c.Exit {
responseSize = c.ResponseSize
return
}
//表单数据自动映射到结构体
if c.Option.AutoMapForm {
a.StructMap(vc, req)
}
//验证XSRF
if c.Option.CheckXsrf {
a.XsrfManager.Init(c)
if req.Method == "POST" {
formVals := req.Form[XSRF_TAG]
var formVal string
if len(formVals) > 0 {
formVal = formVals[0]
}
if formVal == "" ||
!a.XsrfManager.Valid(a.AppConfig.CookiePrefix+
XSRF_TAG, formVal) {
a.error(w, 500, "xsrf token error.")
a.Error("xsrf token error.")
statusCode = 500
return
}
}
}
structName := reflect.ValueOf(reflectType.Name())
actionName := reflect.ValueOf(handlerName)
//执行Before方法
initM = vc.MethodByName("Before")
if initM.IsValid() {
structAction := []reflect.Value{structName, actionName}
if ok := initM.Call(structAction); c.Exit || (len(ok) > 0 && ok[0].Kind() == reflect.Bool && !ok[0].Bool()) {
responseSize = c.ResponseSize
return
}
}
ret, err := a.SafelyCall(vc, handlerName, args)
if err != nil {
//there was an error or panic while calling the handler
if a.AppConfig.Mode == Debug {
a.error(w, 500, fmt.Sprintf("<pre>handler error: %v</pre>", err))
} else if a.AppConfig.Mode == Product {
a.error(w, 500, "Server Error")
}
statusCode = 500
responseSize = c.ResponseSize
return
}
statusCode = fieldA.Interface().(*Action).StatusCode
//执行After方法
initM = vc.MethodByName("After")
if initM.IsValid() {
structAction := []reflect.Value{structName, actionName}
structAction = append(structAction, ret...)
if len(structAction) != initM.Type().NumIn() {
a.Errorf("Error : %v.After(): The number of params is not adapted.", structName)
return
}
ret = initM.Call(structAction)
}
if c.Exit {
responseSize = c.ResponseSize
return
}
if len(ret) == 0 {
defaultResponse(c, nil)
responseSize = c.ResponseSize
return
}
sval := ret[0]
intf := sval.Interface()
kind := sval.Kind()
var content []byte
if intf == nil || kind == reflect.Bool {
responseSize = c.ResponseSize
return
} else if kind == reflect.String {
content = []byte(sval.String())
} else if kind == reflect.Slice && sval.Type().Elem().Kind() == reflect.Uint8 {
content = intf.([]byte)
} else if _, ok := intf.(bool); ok {
responseSize = c.ResponseSize
return
} else if obj, ok := intf.(JSON); ok {
c.ServeJson(obj.Data)
responseSize = c.ResponseSize
return
} else if obj, ok := intf.(JSONP); ok {
c.ServeJsonp(obj.Data, obj.Callback)
responseSize = c.ResponseSize
return
} else if obj, ok := intf.(XML); ok {
c.ServeXml(obj.Data)
responseSize = c.ResponseSize
return
} else if obj, ok := intf.(FILE); ok {
c.ServeFile(obj.Data)
return
} else if obj, ok := intf.(SHOW); ok {
c.Render(obj.Tmpl, obj.T)
return
} else if obj, ok := intf.(JUMP); ok {
c.Redirect(obj.Url, obj.Code)
return
} else if err, ok := intf.(error); ok {
if err != nil {
a.Error("Error:", err)
a.error(w, 500, "Server Error")
statusCode = 500
} else {
responseSize = c.ResponseSize
}
return
} else if str, ok := intf.(string); ok {
content = []byte(str)
} else if byt, ok := intf.([]byte); ok {
content = byt
} else {
var validType bool
Event("OutputBaseOnExtensionName", []interface{}{c, intf}, func(ok bool) {
if !ok {
validType = true
return
}
responseSize, validType = defaultResponse(c, intf)
})
if !validType {
a.Warnf("unknown returned result type %v, ignored %v", kind, intf)
}
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(content)))
size, err := w.Write(content)
if err != nil {
a.Errorf("Error during write: %v", err)
statusCode = 500
return
}
responseSize = int64(size)
return
}
func defaultResponse(c *Action, data interface{}) (responseSize int64, validType bool) {
switch c.ExtensionName {
case "json":
if data == nil {
data = JSONResponse{Status: 1, Message: "", Data: c.T}
}
c.ServeJson(data)
responseSize = c.ResponseSize
validType = true
case "xml":
if data == nil {
data = XMLResponse{Status: 1, Message: "", Data: c.T}
}
c.ServeXml(data)
responseSize = c.ResponseSize
validType = true
}
return
}
func (a *App) error(w http.ResponseWriter, status int, content string) error {
w.WriteHeader(status)
if errorTmpl == "" {
errTmplFile := a.AppConfig.TemplateDir + "/_error.html"
if file, err := os.Stat(errTmplFile); err == nil && !file.IsDir() {
if b, e := ioutil.ReadFile(errTmplFile); e == nil {
errorTmpl = string(b)
}
}
if errorTmpl == "" {
errorTmpl = defaultErrorTmpl
}
}
res := fmt.Sprintf(errorTmpl, status, statusText[status],
status, statusText[status], content, Version)
_, err := w.Write([]byte(res))
return err
}
func (a *App) StaticUrl(url string) string {
var basePath string
if a.AppConfig.StaticDir == RootApp().AppConfig.StaticDir {
basePath = RootApp().BasePath
} else {
basePath = a.BasePath
}
if !a.AppConfig.StaticFileVersion {
return path.Join(basePath, url)
}
ver := a.StaticVerMgr.GetVersion(url)
if ver == "" {
return path.Join(basePath, url)
}
return path.Join(basePath, url+"?v="+ver)
}
// safelyCall invokes `function` in recover block
func (a *App) SafelyCall(vc reflect.Value, method string, args []reflect.Value) (resp []reflect.Value, err error) {
defer func() {
if e := recover(); e != nil {
if !a.Server.Config.RecoverPanic {
// go back to panic
panic(e)
} else {
resp = nil
var content string
content = fmt.Sprintf("Handler crashed with error: %v", e)
for i := 1; ; i += 1 {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
} else {
content += "\n"
}
content += fmt.Sprintf("%v %v", file, line)
}
a.Error(content)
err = errors.New(content)
return
}
}
}()
fn := vc.MethodByName(method)
if fn.Type().NumIn() > 0 {
return fn.Call(args), err
}
return fn.Call(nil), err
}
// Init content-length header.
func (a *App) InitHeadContent(w http.ResponseWriter, contentLength int64) {
if a.ContentEncoding == "gzip" {
w.Header().Set("Content-Encoding", "gzip")
} else if a.ContentEncoding == "deflate" {
w.Header().Set("Content-Encoding", "deflate")
} else {
w.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
}
}
// tryServingFile attempts to serve a static file, and returns
// whether or not the operation is successful.
func (a *App) TryServingFile(name string, req *http.Request, w http.ResponseWriter) (bool, int64) {
newPath := name
if strings.HasPrefix(name, a.BasePath) {
newPath = name[len(a.BasePath):]
}
var size int64
staticFile := filepath.Join(a.AppConfig.StaticDir, newPath)
finfo, err := os.Stat(staticFile)
if err != nil {
return false, size
}
if finfo.IsDir() {
return false, size
}
if a.AppConfig.StaticFileParser != nil {
extName := filepath.Ext(staticFile)
if len(extName) > 0 {
if fn, ok := a.AppConfig.StaticFileParser[strings.ToLower(extName[1:])]; ok {
return fn(staticFile, req, w)
}
}
}
size = finfo.Size()
isStaticFileToCompress := false
if a.Server.Config.EnableGzip && a.Server.Config.StaticExtensionsToGzip != nil && len(a.Server.Config.StaticExtensionsToGzip) > 0 {
for _, statExtension := range a.Server.Config.StaticExtensionsToGzip {
if strings.HasSuffix(strings.ToLower(staticFile), strings.ToLower(statExtension)) {
isStaticFileToCompress = true
break
}
}
}
if isStaticFileToCompress {
a.ContentEncoding = GetAcceptEncodingZip(req)
memzipfile, err := OpenMemZipFile(staticFile, a.ContentEncoding)
if err != nil {
return false, size
}
a.InitHeadContent(w, finfo.Size())
http.ServeContent(w, req, staticFile, finfo.ModTime(), memzipfile)
} else {
http.ServeFile(w, req, staticFile)
}
return true, size
}
// StructMap function mapping params to controller's properties
func (a *App) StructMap(m interface{}, r *http.Request) error {
return a.namedStructMap(m, r, "")
}
// user[name][test]
func SplitJson(s string) ([]string, error) {
res := make([]string, 0)
var begin, end int
var isleft bool
for i, r := range s {
switch r {
case '[':
isleft = true
if i > 0 && s[i-1] != ']' {
if begin == end {
return nil, errors.New("unknow character")
}
res = append(res, s[begin:end+1])
}
begin = i + 1
end = begin
case ']':
if !isleft {
return nil, errors.New("unknow character")
}
isleft = false
if begin != end {
//return nil, errors.New("unknow character")
res = append(res, s[begin:end+1])
begin = i + 1
end = begin
}
default:
end = i
}
if i == len(s)-1 && begin != end {
res = append(res, s[begin:end+1])
}
}
return res, nil
}
func (a *App) namedStructMap(m interface{}, r *http.Request, topName string) error {
vc := reflect.ValueOf(m)
tc := reflect.TypeOf(m)
switch tc.Kind() {
case reflect.Struct:
case reflect.Ptr:
vc = vc.Elem()
tc = tc.Elem()
}
for k, t := range r.Form {
if k == XSRF_TAG || k == "" {
continue
}
if topName != "" {
if !strings.HasPrefix(k, topName) {
continue
}
k = k[len(topName)+1:]
}
v := t[0]
names := strings.Split(k, ".")
var err error