-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
504 lines (452 loc) · 12.2 KB
/
http.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
package middleware
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
)
var mLogger = GetLogger("middleware")
// Server对象
type Server struct {
Host string
Port int
baseTpl *template.Template
pathNodes map[string]pathProcessor
index pathProcessor
restProcessors []func(model interface{}) interface{}
hasIndex bool
CrossDomain bool
status int
filter []filterProcessor
i18n I18n
enableI18n bool
swagger *SwaggerData
sync.RWMutex
}
// 默认全局单一http服务
var globalServer = NewServer("", 0)
// 启动服务
func StartServer(host string, port int) {
globalServer.Lock()
globalServer.Host = host
globalServer.Port = port
globalServer.Unlock()
globalServer.Start()
}
// 获取全局唯一Server
func GetGlobalServer() *Server {
return globalServer
}
// 创建服务
func NewServer(host string, port int) *Server {
srv := Server{
Host: host,
Port: port,
CrossDomain: true,
hasIndex: false,
enableI18n: false,
baseTpl: template.New("middleware.Base"),
swagger: &SwaggerData{
Title: "",
Version: "",
Description: "",
Host: "",
},
}
srv.pathNodes = make(map[string]pathProcessor)
return &srv
}
func (t *Server) GetStatus() int {
t.RLock()
defer t.RUnlock()
return t.status
}
func (t *Server) Start() {
defer func() {
if err := recover(); err != nil {
mLogger.ErrorF("%v", err)
}
}()
t.Lock()
if t.status != 0 {
t.Unlock()
return
}
t.status = 1
t.Unlock()
http.HandleFunc("/", t.ServeHTTP)
hostStr := fmt.Sprintf("%s:%d", t.Host, t.Port)
mLogger.Info("server start " + hostStr)
log.Fatal(http.ListenAndServe(hostStr, nil))
}
var accessLogger = GetCleanLogger("access")
// 核心处理逻辑
func (t *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := TimeEpoch()
startTime := time.Now().Format(TimeFormat)
ctx := newContext(w, r)
ctx.tpl = t.baseTpl
ctx.restProcessors = t.restProcessors
ctx.code = 200 // 是否合适
defer func() {
accessLogger.LogF(`"%v", "%v", "%v", "%v", %v, %v`, startTime, ctx.Request.RequestURI, ctx.Request.RemoteAddr, ctx.GetMethod(), ctx.code, TimeEpoch()-start)
}()
if t.enableI18n {
ctx.EnableI18n = true
ctx.Message = t.i18n
}
if t.CrossDomain {
ctx.SetHeader(AccessControlAllowOrigin, "*")
ctx.SetHeader(AccessControlAllowMethods, METHODS)
ctx.SetHeader(AccessControlAllowHeaders, "*")
if strings.ToUpper(ctx.GetMethod()) == OPTIONS {
ctx.Code(202)
return
}
}
for _, filterNode := range t.filter {
if filterNode.pathReg.MatchString(r.URL.Path) {
if !filterNode.handler(ctx) {
return
}
}
}
if t.hasIndex && r.URL.Path == "/" {
t.index.handler(ctx)
return
}
var handler func(Context)
for _, pathNode := range t.pathNodes {
if pathNode.pathReg.MatchString(r.URL.Path) {
if len(pathNode.params) <= 0 {
handler = pathNode.handler
break
}
pathParams := pathNode.pathReg.FindAllStringSubmatch(r.URL.Path, 10) // 最多10个路径参数
if len(pathParams) > 0 && len(pathParams[0]) > 0 {
for i, pathParam := range pathParams[0][1:] {
if len(pathNode.params) < i+1 {
break
}
ctx.pathParams[pathNode.params[i]] = pathParam
}
}
handler = pathNode.handler
break
}
}
if handler == nil {
ctx.Error(StatusNotFound, StatusNotFoundView)
return
}
handler(ctx)
return
}
type defaultIndexStruct struct {
Style string
Title string
BackgroundUrl string
HeaderLinks string
CenterContent string
PoweredBy string
FooterLinks string
Buttons string
}
type DefaultIndexStruct struct {
Title string
BackgroundUrl string
HeaderLinks []DefaultIndexLink
CenterContentLines []string
Buttons []DefaultIndexLink
PoweredBy string
FooterLinks []DefaultIndexLink
ExtendedStyle string
EnableSwagger bool
}
type DefaultIndexLink struct {
Text string
Link string
}
// RegisterDefaultIndex 注册默认的主页, link格式为: name,link
// DefaultIndex title, backgroundUrl headerLinks, centerContent, enterLink, poweredBy, footerLinks
func (t *Server) RegisterDefaultIndex(params DefaultIndexStruct) {
// <a class="nav-link" href="/swagger-ui" target="_blank">Swagger</a>
headerlinkTpl := `<a class="nav-link" href="${link}" target="_blank">${text}</a>`
footerLinkTpl := `<a href="${link}" target="_blank" class="text-white">${text}</a>`
buttonTpl := `<a href="${link}" class="btn btn-lg btn-secondary fw-bold border-white bg-white">${text}</a>`
centerContentTpl := `<p class="lead">%s</p>`
centerContent := ""
headerLink := ""
footerLink := ""
if len(params.HeaderLinks) > 0 {
for _, link := range params.HeaderLinks {
headerLink = fmt.Sprintf("%s %s", headerLink, StringFormatStructs(headerlinkTpl, link))
}
}
if params.EnableSwagger {
headerLink = fmt.Sprintf("%s %s", headerLink, `<a class="nav-link" href="/swagger-ui" target="_blank">Swagger</a>`)
}
if len(params.FooterLinks) > 0 {
for _, link := range params.FooterLinks {
footerLink = fmt.Sprintf("%s, %s", footerLink, StringFormatStructs(footerLinkTpl, link))
}
}
if len(params.CenterContentLines) > 0 {
for _, center := range params.CenterContentLines {
centerContent = fmt.Sprintf("%s %s", centerContent, fmt.Sprintf(centerContentTpl, strings.TrimSpace(center)))
}
}
if len(params.BackgroundUrl) <= 0 {
params.BackgroundUrl = "/static/default/images/default_background"
t.RegisterHandler(params.BackgroundUrl, func(context Context) {
context.AddCacheHeader(3600 * 24 * 30)
context.OK(Jpeg, defaultBackground)
})
}
buttons := ""
if len(params.Buttons) > 0 {
for _, btn := range params.Buttons {
buttons = fmt.Sprintf("%s %s", buttons, StringFormatStructs(buttonTpl, btn))
}
}
t.RegisterHandler("/static/default/css/bootstrap.v5.min", func(context Context) {
context.OK(Css, []byte(BootstrapCss))
})
t.RegisterIndex(func(context Context) {
context.OK(Html, []byte(StringFormatStructs(DefaultIndex, defaultIndexStruct{
Style: params.ExtendedStyle,
Title: params.Title,
BackgroundUrl: params.BackgroundUrl,
HeaderLinks: headerLink,
CenterContent: centerContent,
PoweredBy: params.PoweredBy,
FooterLinks: footerLink,
Buttons: buttons,
})))
})
}
// 设置静态文件目录
func (t *Server) Static(path string) {
if !strings.HasSuffix(path, "/") {
path = fmt.Sprintf("%s/", path)
}
t.RegisterHandler(path, StaticProcessor)
}
// 注册首页
func (t *Server) RegisterIndex(handler func(Context)) {
t.Lock()
defer t.Unlock()
t.hasIndex = true
t.index = pathProcessor{
handler: handler,
}
}
// 结合 react 前端, 注册前端dist目录
func (t *Server) RegisterFrontendDist(distPath string, prefix string) {
exp := regexp.MustCompile(`\.html$|\.js$|\.jsx$|\.ts$|\.tsx$|\.css$|\.svg$|\.icon$|\.ico$|\.png$|\.jpg$|\.jpeg$|\.gif$`)
filterPath := "/.*"
if len(prefix) > 0 {
if !strings.HasSuffix(prefix, "/") {
prefix = fmt.Sprintf("%v/", prefix)
}
if !strings.HasPrefix(prefix, "/") {
prefix = fmt.Sprintf("/%v", prefix)
}
filterPath = fmt.Sprintf("%v.*", prefix)
}
t.RegisterFilter(filterPath, func(context Context) bool {
if exp.MatchString(context.Request.URL.Path) {
urlPath := context.Request.URL.Path
if len(prefix) > 0 {
urlPath = strings.Replace(urlPath, prefix, "", 1)
}
filePath := fmt.Sprintf("%s/%s", distPath, urlPath)
http.ServeFile(context.Response, context.Request, filePath)
return false
}
return true
})
if len(prefix) > 0 {
t.RegisterHandler(prefix[:(len(prefix)-1)], func(context Context) {
println(context.Request.URL.Path)
http.ServeFile(context.Response, context.Request, fmt.Sprintf("%s/index.html", distPath))
})
t.RegisterHandler(prefix, func(context Context) {
println(context.Request.URL.Path)
http.ServeFile(context.Response, context.Request, fmt.Sprintf("%s/index.html", distPath))
})
} else {
t.RegisterIndex(func(context Context) {
http.ServeFile(context.Response, context.Request, fmt.Sprintf("%s/index.html", distPath))
})
}
}
func RegisterDefaultIndex(params DefaultIndexStruct) {
globalServer.RegisterDefaultIndex(params)
}
// 注册首页处理器
func RegisterIndex(handler func(Context)) {
globalServer.RegisterIndex(handler)
}
// 注册静态文件目录
func RegisterStatic(path string) {
globalServer.Static(path)
}
// 注册前端编译后程序路径
func RegisterFrontendDist(distPath string, prefix string) {
globalServer.RegisterFrontendDist(distPath, prefix)
}
// 注册模板服务
func (t *Server) RegisterTemplate(filePath string) {
t.Lock()
var err error
t.baseTpl, err = includeTemplate(t.baseTpl, ".html", []string{filePath}...)
if err != nil {
mLogger.Error(err.Error())
}
t.Unlock()
mLogger.InfoF("render template %v done!", filePath)
}
// 注册模板服务
func RegisterTemplate(filePath string) {
globalServer.RegisterTemplate(filePath)
}
// 注册模板函数
// warning: 请在设置模板目录前使用
func (t *Server) TemplateFunc(name string, function interface{}) {
t.Lock()
defer t.Unlock()
t.baseTpl.Funcs(template.FuncMap{
name: function})
}
// 注册模板函数
// warning: 请在设置模板目录前使用
func TemplateFunc(name string, function interface{}) {
globalServer.TemplateFunc(name, function)
}
func includeTemplate(tpl *template.Template, suffix string, filePaths ...string) (*template.Template, error) {
fileList := make([]string, 0)
for _, filePath := range filePaths {
info, err := os.Stat(filePath)
if err != nil {
mLogger.Error(err.Error())
continue
}
if info.IsDir() {
_ = filepath.Walk(filePath, func(path string, innerInfo os.FileInfo, err error) error {
if !innerInfo.IsDir() {
// 后缀名过滤
if filepath.Ext(innerInfo.Name()) == suffix {
fileList = append(fileList, path)
}
}
return nil
})
} else {
if filepath.Ext(filePath) == suffix {
fileList = append(fileList, filePath)
}
}
}
mLogger.InfoLn("获取模板文件列表")
mLogger.InfoLn(strings.Join(fileList, ","))
if tpl == nil {
return template.ParseFiles(fileList...)
}
return tpl.ParseFiles(fileList...)
}
// 注册http请求处理器
//
// @param path:路径, 可以用 {占位符} 进行路径参数设置
func RegisterHandler(path string, handler func(Context)) {
globalServer.RegisterHandler(path, handler)
}
func (t *Server) SetI18n(name string) {
if len(name) <= 0 {
name = "message"
}
cn := LoadConfig(fmt.Sprintf("%s_cn.properties", name))
en := LoadConfig(fmt.Sprintf("%s_en.properties", name))
t.i18n = I18n{
Cn: cn,
En: en,
}
t.enableI18n = true
}
func SetI18n(name string) {
globalServer.SetI18n(name)
}
var pathParamReg, _ = regexp.Compile("\\{(.+?)\\}")
// 注册服务
func (t *Server) RegisterHandler(path string, handler func(Context)) {
t.Lock()
defer t.Unlock()
if len(path) <= 0 {
return
}
if handler == nil {
return
}
var params = []string{}
paramMather := pathParamReg.FindAllStringSubmatch(path, -1)
for _, param := range paramMather {
params = append(params, param[1])
path = strings.Replace(path,
param[0], "(.+?)", -1)
}
if strings.HasSuffix(path, "/") {
path = fmt.Sprintf("%s.*", path)
} else {
path = fmt.Sprintf("%s$", path)
}
if !strings.HasPrefix(path, "/") {
path = fmt.Sprintf("/%s", path)
}
path = fmt.Sprintf("^%s", path)
pathReg, err := regexp.Compile(path)
mLogger.InfoF("注册handler: %s", path)
if !ProcessError(err) {
t.pathNodes[path] = pathProcessor{
pathReg: pathReg,
handler: handler,
params: params,
}
}
}
func (t *Server) RegisterRestProcessor(processor func(model interface{}) interface{}) {
t.Lock()
t.restProcessors = append(t.restProcessors, processor)
t.Unlock()
mLogger.InfoLn("新增restProcessor")
}
type pathProcessor struct {
pathReg *regexp.Regexp
params []string
handler func(Context)
}
type starProcessor struct {
pathReg *regexp.Regexp
handler func(Context)
}
func StaticProcessor(ctx Context) {
ctx.code = 200
http.ServeFile(ctx.Response, ctx.Request, ctx.Request.URL.Path[1:])
}
// 错误处理
//
// return true 错误发生
//
// false 无错误
func ProcessError(err error) bool {
if err != nil {
mLogger.Error(err.Error())
return true
}
return false
}