/
leafveingo.go
1757 lines (1491 loc) · 40.4 KB
/
leafveingo.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
// Copyright 2013 slowfei And The Contributors All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Create on 2013-08-16
// Update on 2015-08-03
// Email slowfei#nnyxing.com
// Home http://www.slowfei.com
// version 0.0.2.000
//
// Leafveingo web framework
//
package leafveingo
import (
"bytes"
"crypto/tls"
"flag"
"fmt"
"github.com/slowfei/gosfcore/debug"
"github.com/slowfei/gosfcore/helper"
"github.com/slowfei/gosfcore/log"
"github.com/slowfei/gosfcore/utils/filemanager"
"github.com/slowfei/gosfcore/utils/strings"
"github.com/slowfei/leafveingo/session"
"github.com/slowfei/leafveingo/template"
"io"
"io/ioutil"
"net"
"net/http"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
// leafveingo version
VERSION string = "0.0.2.000"
// template func key
TEMPLATE_FUNC_KEY_VERSION = "Leafveingo_version"
TEMPLATE_FUNC_KEY_APP_VERSION = "Leafveingo_app_version"
TEMPLATE_FUNC_KEY_APP_NAME = "Leafveingo_app_name"
TEMPLATE_FUNC_KEY_IS_DEVEL = "Leafveingo_devel"
// 不知道为什么golang使用http.ServeFile判断为此结尾就重定向到/index.html中。
// 这里定义主要用来解决这个问题的处理
INDEX_PAGE = "/index.html"
//
FAVICON_PATH = "/favicon.ico"
// url params host key
URL_HOST_KEY = "host"
// hosts www
URL_HOST_WWW = "www."
URL_HOST_WWW_LEN = 4
// uri schemes
URI_SCHEME_HTTP = URIScheme(1) // http
URI_SCHEME_HTTPS = URIScheme(2) // https
)
var (
// 开发模式命令
FlagDeveloper bool
// init server memory list
_serverList []*LeafveinServer = nil
//
_serverWaitGroup *sync.WaitGroup = nil
)
func init() {
flag.BoolVar(&FlagDeveloper, "devel", false, "developer mode start.")
}
//#pragma mark leafveingo func ----------------------------------------------------------------------------------------------------
/**
* global start all leafvein server
*
*/
func Start() {
if 0 == len(_serverList) {
SFLog.Fatal("no to start the leafvein server.")
return
}
_serverWaitGroup = new(sync.WaitGroup)
count := len(_serverList)
for i := 0; i < count; i++ {
server := _serverList[i]
server.Start(true)
}
_serverWaitGroup.Wait()
}
/**
* global close all leafvein server
*
*/
func Close() {
if 0 == len(_serverList) {
SFLog.Fatal("no to close the leafvein server.")
return
}
count := len(_serverList)
for i := 0; i < count; i++ {
server := _serverList[i]
server.Close()
}
}
func SetLogManager(channelSize int) {
// SFLog.StartLogManager(lv.logChannelSize)
SFLog.StartLogManager(channelSize)
}
/**
* by app name get leafvein server
*
* @param appName
* @return
*/
func GetServer(appName string) *LeafveinServer {
count := len(_serverList)
for i := 0; i < count; i++ {
server := _serverList[i]
if appName == server.AppName() {
return server
}
}
return nil
}
/**
* leafveion version info
*
* @return
*/
func Version() string {
return VERSION
}
/**
* private add server
*
* @param server
*/
func addServerList(server *LeafveinServer) {
if nil != GetServer(server.AppName()) {
panic(ErrLeafveinAppNameRepeat)
}
_serverList = append(_serverList, server)
}
//#pragma mark uri scheme type ----------------------------------------------------------------------------------------------------
//
// uri scheme
//
type URIScheme int
/**
* scheme string
*
* @return string tag
*/
func (u URIScheme) String() string {
result := ""
comma := false
if u&URI_SCHEME_HTTP == URI_SCHEME_HTTP {
result += "http"
comma = true
}
if u&URI_SCHEME_HTTPS == URI_SCHEME_HTTPS {
if comma {
result += ",https"
} else {
result += "https"
}
comma = true
}
return result
}
//#pragma mark ServerOption struct ----------------------------------------------------------------------------------------------------
/**
* Leafvein Server option
*
* use DefaultOption() see default value
*/
type ServerOption struct {
// ip access "127.0.0.1" localhost access
// all address access
// "192.168.?.?" specify access
// default "127.0.0.1"
Addr string
Port int // ip port. default 8080
SMGCTime int64 // session manager gc operate time. 0 is not run session, minimum 60 second. default 300
ConfigPath string // relative or absolute path, relative path from execute file root directory, can set empty. default ""
}
/**
* default server option value
*/
func DefaultOption() ServerOption {
option := ServerOption{}
option.Addr = "127.0.0.1"
option.Port = 8080
option.SMGCTime = LVSession.DEFAULT_SCAN_GC_TIME
option.ConfigPath = ""
return option
}
/**
* set addr
*/
func (s ServerOption) SetAddr(addr string) ServerOption {
s.Addr = addr
return s
}
/**
* set port
*/
func (s ServerOption) SetPort(port int) ServerOption {
s.Port = port
return s
}
/**
* set session manager operate gc
*/
func (s ServerOption) SetSMGCTime(second int64) ServerOption {
s.SMGCTime = second
return s
}
/**
* set config file path
*/
func (s ServerOption) SetConfigPath(path string) ServerOption {
s.ConfigPath = path
return s
}
/**
* checked params
*/
func (s *ServerOption) Checked() {
if 60 > s.SMGCTime {
s.SMGCTime = 60
}
}
//# mark LeafveinServer struct ----------------------------------------------------------------------------------------------------
//
// Leafvein Http Server
//
type LeafveinServer struct {
/* #mark require params ******************/
appName string // application info default LeafveingoWeb
addr string // "127.0.0.1" | "" | "192.168.?.?"
port int // 8080 | 8090 ...
/* #mark optional params, see detailed defaults value to config.go _defaultConfigJson ******************/
appVersion string // app version
fileUploadSize int64 // file size upload
charset string // html encode type
staticFileSuffixes map[string]string // supported static file suffixes
serverTimeout int64 // server time out, default 0
sessionMaxlifeTime int32 // http session maxlife time, unit second. use session set
ipHeaderKey string // proxy to http headers set ip key, default ""
isReqPathIgnoreCase bool // request url path ignore case
multiProjectHosts []string // setting integrated multi-project hosts
templateSuffix string // template suffix
isCompactHTML bool // is Compact HTML, default true
logConfigPath string // log config path, relative or absolute path, relative path from execute file root directory
logGroup string // log group name
tlsCertPath string // tls cert.pem, relative or absolute path, relative path from execute file root directory
tlsKeyPath string // tls key.pem
tlsPort int // tls run prot, default server port+1
tlsAloneRun bool // are leafveingo alone run tls server
// is ResponseWriter writer compress gizp...
// According Accept-Encoding select compress type
// default true
isRespWriteCompress bool
userData map[string]string // user custom config other info
/* #mark router patams ******************/
// all router storage map and router keys
routerList []*RouterElement
/* #mark system patams ******************/
application *SFHelper.Map // application
sessionManager *LVSession.HttpSessionManager // http session manager
template *LVTemplate.Template // template
log *SFLog.SFLogger // log
config *Config // config info
correctRequestFunc func(req *http.Request) // modify request, before server request call.
// current leafveingo the file operation directory
// operatingDir 是根据 appName 建立的目录路径
operatingDir string
memWebRootDir string // memory storage
memTemplateDir string // memory storage
prefix string // http url prefix
listener net.Listener // current http listener
tlsListener net.Listener // tls listener
isDevel bool // developer mode
isStart bool // is start
}
//# mark LeafveinServer init ----------------------------------------------------------------------------------------------------
/**
* new http server
*
* @param appName application name not is null
* @param option server other option
*/
func NewLeafveinServer(appName string, option ServerOption) *LeafveinServer {
if 0 == len(appName) {
return nil
}
option.Checked()
server := &LeafveinServer{appName: appName, addr: option.Addr, port: option.Port}
// set other params
server.initPrivate(option)
// add to server list
addServerList(server)
return server
}
/**
* init optional params
*/
func (lv *LeafveinServer) initPrivate(option ServerOption) {
lv.template = LVTemplate.NewTemplate()
lv.template.SetFunc(TEMPLATE_FUNC_KEY_VERSION, Version)
lv.template.SetFunc(TEMPLATE_FUNC_KEY_APP_NAME, lv.AppName)
lv.template.SetFunc(TEMPLATE_FUNC_KEY_APP_VERSION, lv.AppVersion)
lv.template.SetFunc(TEMPLATE_FUNC_KEY_IS_DEVEL, lv.IsDevel)
lv.config = new(Config)
lv.configLoadDefault()
// config handle
if 0 != len(option.ConfigPath) {
err := configLoadByFilepath(option.ConfigPath, lv.config)
if nil != err {
lilcErr := *ErrLeafveinInitLoadConfig
lilcErr.UserInfo = err.Error()
panic(&lilcErr)
return
}
lv.configReload(lv.config)
}
lv.isStart = false
lv.application = SFHelper.NewMap()
lv.operatingDir = filepath.Join(SFFileManager.GetExecDir(), lv.appName)
// start session manager
if 60 <= option.SMGCTime {
lv.SetHttpSessionManager(LVSession.NewSessionManagerAtGCTime(option.SMGCTime, true))
}
}
//# mark LeafveinServer private method -------------------------------------------------------------------------------------------
/**
* closed free resources
*/
func (lv *LeafveinServer) free() {
// TODO Temporarily invalid, keep extension
}
/**
* load default config info
*/
func (lv *LeafveinServer) configLoadDefault() {
err := configLoadByJson([]byte(_defaultConfigJson), lv.config)
if nil != err {
lldcErr := *ErrLeafveinLoadDefaultConfig
lldcErr.UserInfo = err.Error()
panic(&lldcErr)
return
}
lv.configReload(lv.config)
}
/**
* reload config info
*
* @param cf
*/
func (lv *LeafveinServer) configReload(cf *Config) {
lv.SetAppVersion(cf.AppVersion)
lv.SetFileUploadSize(cf.FileUploadSize)
lv.SetCharset(cf.Charset)
lv.SetStaticFileSuffixes(cf.StaticFileSuffixes...)
lv.SetSessionMaxlifeTime(cf.SessionMaxlifeTime)
lv.SetIPHeaderKey(cf.IPHeaderKey)
lv.SetReqPathIgnoreCase(cf.IsReqPathIgnoreCase)
lv.SetTemplateSuffix(cf.TemplateSuffix)
lv.SetRespWriteCompress(cf.IsRespWriteCompress)
lv.SetMultiProjectHosts(cf.MultiProjectHosts...)
lv.userData = cf.UserData
// restart
lv.SetServerTimeout(cf.ServerTimeout)
lv.SetCompactHTML(cf.IsCompactHTML)
lv.SetLogConfigPath(cf.LogConfigPath)
lv.SetLogGroup(cf.LogGroup)
lv.SetHttpTLS(cf.TLSCertPath, cf.TLSKeyPath, cf.TLSPort, cf.TLSAloneRun)
}
/**
* status page response writer set content-type and header code
* 不使用压缩的输出的
*
* @param rw
* @param value
*/
func (lv *LeafveinServer) statusPageWriter(value HttpStatusValue, rw http.ResponseWriter) error {
rw.Header().Set("Content-Encoding", "none")
rw.Header().Set("Content-Type", "text/html; charset="+lv.Charset())
rw.WriteHeader(int(value.status))
return lv.statusPageExecute(value, rw)
}
/**
* status page template execute
*
* @param wr
* @param value
*/
func (lv *LeafveinServer) statusPageExecute(value HttpStatusValue, wr io.Writer) error {
status := strconv.Itoa(int(value.status))
// 根据状态代码先查找模版,直接查找模版的根目录
tplName := status + lv.TemplateSuffix()
tmpl, err := lv.template.Parse(tplName)
if nil != err {
tmpl, err = lv.template.ParseString(tplName, HttpStartTemplate)
if nil != err {
return err
}
}
return tmpl.Execute(wr, value.data)
}
/**
* parse router
*
* @param logInfo
* @param startName
* @return success == true
*/
func (lv *LeafveinServer) parseRouter(logInfo *string, startName string) bool {
// memory storage
lv.memTemplateDir = filepath.Join(lv.operatingDir, DEFAULT_TEMPLATE_DIR_NAME)
lv.memWebRootDir = filepath.Join(lv.operatingDir, DEFAULT_WEBROOT_DIR_NAME)
// log manager
SFLog.LoadConfig(lv.logConfigPath)
logTag := fmt.Sprintf("Leafvein(%s)", lv.appName)
if 0 != len(lv.LogGroup()) {
lv.log = SFLog.NewLoggerByGroup(logTag, lv.LogGroup())
} else {
lv.log = SFLog.NewLogger(logTag)
}
// template
lv.template.SetBaseDir(lv.TemplateDir())
lv.template.SetCache(!lv.isDevel)
lv.template.SetDevel(lv.IsDevel())
// add global touter
for _, router := range _globalRouterList {
if router.appName == lv.AppName() {
lv.AddRouter(router.router)
}
}
// validate routerList nil
if 0 == len(lv.routerList) {
lv.log.Fatal("LeafveinServer %v fatal: routerList == nil \n", startName)
return false
}
// validate folder
if isExites, isDir, _ := SFFileManager.Exists(lv.operatingDir); !isExites || !isDir {
lv.log.Warn("not locate the operating directory, will not be able to manipulate files,\n %v \n operation directory is created under the app name directory \n", lv.operatingDir)
}
if isExites, isDir, _ := SFFileManager.Exists(lv.WebRootDir()); !isExites || !isDir {
lv.log.Warn("not locate the %v directory, will not be able to read a static file resource and upload file. \n need to create directory: %v \n", lv.WebRootDir(), lv.WebRootDir())
}
// print config info
configBuf := bytes.NewBufferString("")
SFDebug.Fdump(configBuf, true, lv.config)
*logInfo += "config:\n" + configBuf.String()
// print log info
*logInfo += "controller:\n"
for _, element := range lv.routerList {
for _, key := range element.routerKeys {
if router, ok := element.routers[key]; ok {
*logInfo += fmt.Sprintf("host:[%#v][%v] key:[%#v] %v\n", element.host, router.ControllerOption().Scheme().String(), key, router.Info())
} else {
*logInfo += fmt.Sprintf("schemes[%v][%v] host:[%#v] key:[%#v] controller stores error.", element.host, router.ControllerOption().Scheme().String(), key)
}
}
}
*logInfo += "\n"
return true
}
/**
* start leafvein server
*
* @param startName "DevelStart" or "Start"
* @param goroutine
*/
func (lv *LeafveinServer) start(startName string, goroutine bool) {
if lv.IsStart() {
return
}
var runFunc func() = nil
var defaultServer *http.Server = nil
// start info
logInfo := fmt.Sprintf("(%v)Leafvein %v...\n", lv.AppName(), startName)
if !lv.parseRouter(&logInfo, startName) {
return
}
if 0 >= lv.port {
lv.port = 8080
}
addr := fmt.Sprintf("%s:%d", lv.addr, lv.port)
// 由于addr设置为127.0.0.1的时候就只能允许内网进行http://localhost:(port)/进行访问,本机IP访问不了。
// 为了友好的显示,如果addr设置为空的时候允许IP或localhost进行访问做了特别的显示除了(http://0.0.0.0:8080)
logAddr := ""
logTLSAddr := ""
if strings.Index(addr, ":") == 0 {
logAddr = "http://0.0.0.0" + addr
logTLSAddr = "https://0.0.0.0"
} else {
logAddr = "http://" + addr
logTLSAddr = "https://" + lv.addr
}
if 0 == len(lv.tlsCertPath) || 0 == len(lv.tlsKeyPath) || !lv.tlsAloneRun {
// default server and listen
defaultServer = &http.Server{
Addr: addr,
Handler: lv,
ReadTimeout: time.Duration(lv.serverTimeout) * time.Second,
WriteTimeout: time.Duration(lv.serverTimeout) * time.Second,
}
netListen, err := net.Listen("tcp", addr)
if err != nil {
lv.log.Fatal("(%v) %v Listen: %v \n", lv.appName, startName, err)
return
}
lv.listener = &leafveinListener{netListen.(*net.TCPListener), DEFAULT_KEEP_ALIVE_PERIOD, nil}
}
// handle tls
if 0 != len(lv.tlsCertPath) && 0 != len(lv.tlsKeyPath) {
// see http://golang.org/src/pkg/net/http/server.go?#L1823
certFullpath := lv.tlsCertPath
if !filepath.IsAbs(certFullpath) {
certFullpath = filepath.Join(SFFileManager.GetExecDir(), lv.tlsCertPath)
}
keyFullpath := lv.tlsKeyPath
if !filepath.IsAbs(keyFullpath) {
keyFullpath = filepath.Join(SFFileManager.GetExecDir(), lv.tlsKeyPath)
}
certPEMBlock, err := ioutil.ReadFile(certFullpath)
if nil != err {
lv.log.Fatal("(%v) %v Serve Read SSL cert file: %v \n", lv.appName, startName, err)
return
}
keyPEMBlock, err := ioutil.ReadFile(keyFullpath)
if nil != err {
lv.log.Fatal("(%v) %v Serve Read SSL key file: %v \n", lv.appName, startName, err)
return
}
if 0 == lv.tlsPort {
lv.tlsPort = lv.port + 1
}
tlsServer := &http.Server{
Addr: fmt.Sprintf("%s:%d", lv.addr, lv.tlsPort),
Handler: lv,
ReadTimeout: time.Duration(lv.serverTimeout) * time.Second,
WriteTimeout: time.Duration(lv.serverTimeout) * time.Second,
}
tlsServer.TLSConfig = new(tls.Config)
tlsServer.TLSConfig.NextProtos = []string{"http/1.1"}
tlsServer.TLSConfig.Certificates = make([]tls.Certificate, 1)
tlsServer.TLSConfig.Certificates[0], err = tls.X509KeyPair(certPEMBlock, keyPEMBlock)
if nil != err {
lv.log.Fatal("(%v) %v TLS Serve: %v \n", lv.appName, startName, err)
return
}
tlsListen, err := net.Listen("tcp", tlsServer.Addr)
if err != nil {
lv.log.Fatal("(%v) %v TLS Listen: %v \n", lv.appName, startName, err)
return
}
// http start
if nil != lv.listener && nil != defaultServer {
logInfo += fmt.Sprintf("(%v) %v to Listen on %v. Go to %v \n", lv.appName, startName, lv.port, logAddr)
go func() {
err = defaultServer.Serve(lv.listener)
if err != nil {
lv.log.Fatal("(%v) %v Serve: %v \n", lv.appName, startName, err)
}
}()
}
// tls start
lv.tlsListener = &leafveinListener{tlsListen.(*net.TCPListener), DEFAULT_KEEP_ALIVE_PERIOD, tlsServer.TLSConfig}
logInfo += fmt.Sprintf("(%v) %v to TLS Listen on %v. Go to %v:%v \n", lv.appName, startName, lv.tlsPort, logTLSAddr, lv.tlsPort)
lv.log.Info(logInfo)
runFunc = func() {
err = tlsServer.Serve(lv.tlsListener)
if err != nil {
lv.log.Fatal("(%v) %v TLS Serve: %v \n", lv.appName, startName, err)
}
lv.isStart = false
if nil != _serverWaitGroup {
_serverWaitGroup.Done()
}
}
} else {
if nil == defaultServer || nil == lv.listener {
lv.log.Fatal("default server or default listener init nil. port is configured correctly?")
return
}
logInfo += fmt.Sprintf("(%v) %v to Listen on %v. Go to %v \n", lv.appName, startName, lv.port, logAddr)
lv.log.Info(logInfo)
runFunc = func() {
err := defaultServer.Serve(lv.listener)
if err != nil {
lv.log.Fatal("(%v) %v Serve: %v \n", lv.appName, startName, err)
}
lv.isStart = false
if nil != _serverWaitGroup {
_serverWaitGroup.Done()
}
}
}
// start server
lv.isStart = true
if nil != _serverWaitGroup {
_serverWaitGroup.Add(1)
}
if goroutine {
go runFunc()
} else {
runFunc()
}
}
/**
* defer func ServeHTTP(...)
*
* @param context
*/
func (lv *LeafveinServer) deferServeHTTP(contextPrt **HttpContext, rw http.ResponseWriter) {
context := *contextPrt
if err := recover(); err != nil {
errStr := fmt.Sprintln(err)
// print stack
stackBuf := bytes.NewBufferString("")
for i := 2; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fn := runtime.FuncForPC(pc).Name()
if 0 != len(file) {
// /usr/local/go/src/pkg/runtime/proc.c:1223 (0x173d0)
fmt.Fprintf(stackBuf, "%s(...)\n%s:%d (0x%x)\n", fn, file, line, pc)
} else {
// runtime.goexit(...)
// L1223: runtime.goexit(...) (0x173d0)
fmt.Fprintf(stackBuf, "L%d: %s(...) (0x%x)\n", line, fn, pc)
}
}
// page write
if nil != context {
if lv.isDevel {
context.StatusPageWrite(Status500, Status500Msg, errStr, stackBuf.String())
} else {
context.StatusPageWrite(Status500, Status500Msg, "", "")
}
} else {
if lv.isDevel {
lv.statusPageWriter(NewHttpStatusValue(Status500, Status500Msg, errStr, stackBuf.String()), rw)
} else {
lv.statusPageWriter(NewHttpStatusValue(Status500, Status500Msg, "", ""), rw)
}
}
fmt.Fprintf(stackBuf, "\n-----------------------------\nleafveiongo version:%v \ngolang version: %v", Version(), runtime.Version())
lv.log.Error("panic error.\nerror info: " + errStr + "\nstack:\n" + stackBuf.String())
}
if nil != context {
context.free()
}
}
/**
* handle request URL
*
* @param rw
* @param req
* @return reqSuffix request url suffix
* @return reqHost request url host
* @return pass is true continue other operations
*/
func (lv *LeafveinServer) requestURLHandle(rw http.ResponseWriter, req *http.Request, reqPath string) (reqSuffix, reqHost string, pass bool) {
pass = true
// 前缀url清除,call GetHandlerFunc() 才会使用到此操作
// /expand/index = /index
// /expand = /
if 0 < len(lv.prefix) {
reqPath = reqPath[len(lv.prefix):]
if 0 != len(reqPath) && '/' != reqPath[0] {
reqPath = "/" + reqPath
}
}
if 0 == len(reqPath) {
reqPath = "/"
}
// request suffix, host
reqSuffix = path.Ext(reqPath)
hostsCount := len(lv.multiProjectHosts)
if 0 != hostsCount {
reqHost = SFStringsUtil.ToLower(req.Host)
reqHostLen := len(reqHost)
if 0 == reqHostLen {
pass = false
errorMsg := ""
if lv.IsDevel() {
errorMsg = "Request Host null"
}
lv.statusPageWriter(NewHttpStatusValue(Status400, Status400Msg, errorMsg, ""), rw)
return
}
// remove port
retScope := reqHostLen - 7
if 0 > retScope {
retScope = 0
}
index := -1
for i := reqHostLen - 1; i >= retScope; i-- {
if ':' == reqHost[i] {
index = i
break
}
}
if -1 != index {
reqHost = reqHost[:index]
}
// replace 127.0.0.1 host
if lv.IsDevel() {
if "localhost" == reqHost || "127.0.0.1" == reqHost {
urlHost := req.URL.Query().Get(URL_HOST_KEY)
if 0 != len(urlHost) {
reqHost = urlHost
}
}
}
// remove "www."
if URL_HOST_WWW_LEN < len(reqHost) && URL_HOST_WWW == reqHost[URL_HOST_WWW_LEN:] {
reqHost = reqHost[:URL_HOST_WWW_LEN]
}
// checked multi-project host
pass = false
for i := 0; i < hostsCount; i++ {
proHost := lv.multiProjectHosts[i]
if proHost == reqHost {
pass = true
break
}
}
if !pass {
errorMsg := ""
if lv.IsDevel() {
errorMsg = "Host(" + req.Host + ") invalid"
}
lv.statusPageWriter(NewHttpStatusValue(Status404, Status404Msg, errorMsg, ""), rw)
return
}
}
return
}
/**
* static file handle
*
* @param rw
* @param req
* @param reqPath request url path
* @param reqSuffix request url suffix
* @return pass is true continue other operations
*/
func (lv *LeafveinServer) staticFileHandle(rw http.ResponseWriter, req *http.Request, reqPath, reqSuffix, reqHost string) (pass bool) {
pass = true
if _, ok := lv.staticFileSuffixes[reqSuffix]; ok {
var filePath string
if 0 != len(reqHost) {
filePath = lv.WebRootDir() + "/" + reqHost + reqPath
} else {
filePath = lv.WebRootDir() + reqPath
}
// TODO 考虑使用Join链接路径,然后join后的路径控制在WebRoot目录内的范围,不可越过WebRoot路径。
if isExists, isDir, _ := SFFileManager.Exists(filePath); isExists && !isDir {
// 处理http.ServeFile函数遇到/index.html被重定向到./的问题
if strings.HasSuffix(reqPath, INDEX_PAGE) {
// 防止serveFile做判断,具体可以查看http.ServeFile源码
req.URL.Path = "/"
}
http.ServeFile(rw, req, filePath)
pass = false
return
} else {
// favicon.ico 找不到直接跳过
if FAVICON_PATH == reqPath {
pass = false
}
}
// 查找不到静态文件交由路由器处理
// else {
// // 404
// // http.NotFound(rw, req)
// lv.statusPageWriter(NewHttpStatusValue(Status404, Status404Msg, "", ""), rw)
// }
}
return
}
//# mark LeafveinServer public method --------------------------------------------------------------------------------------------
/**
* start leafvein server
*
* @param goroutine true is go func(){ // run serve }(), 关键保留一些操作在主线程来运行, 不知道的可以false
*/
func (lv *LeafveinServer) Start(goroutine bool) {
if !flag.Parsed() {
flag.Parse()
}
lv.isDevel = FlagDeveloper
if FlagDeveloper {
lv.start("DevelStart", goroutine)
} else {
args := flag.Args()
if 0 < len(args) {
fmt.Println("incorrect command arguments. \n [-devel] = developer mode, [(nil)] = produce mode.")
return
}
lv.start("Start", goroutine)
}
}
/**
* 获取leafveingo的一个Handler, 方便在其他应用进行扩展leafveingo
* get leafveingo handler, Easily be extended to other applications
*
* @prefix url prefix
*/
func (lv *LeafveinServer) GetHandlerFunc(prefix string) (handler http.Handler, err error) {
if 2 > len(prefix) || prefix[0] != '/' {
err = NewLeafveinError("GetHandlerFunc(...) prefix error : %#v reference ( \"/expand\" )", prefix)
return
}
logInfo := fmt.Sprintf("GetHandlerFunc() parse router...\n")
if !lv.parseRouter(&logInfo, "HandlerFunc") {
return
}
lv.log.Info(logInfo)
f := func(w http.ResponseWriter, r *http.Request) {
// 匹配前缀
if strings.HasPrefix(r.URL.Path, lv.prefix) {