-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.go
More file actions
180 lines (162 loc) · 4.17 KB
/
Copy pathweb.go
File metadata and controls
180 lines (162 loc) · 4.17 KB
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
package bootx
import (
"fmt"
"github.com/gen-iot/std"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"net/http"
"os"
"strings"
"sync"
)
const HeaderAuthorization = echo.HeaderAuthorization
const (
DefaultHttpPort = 8080
DefaultStaticRoot = ""
DefaultWebBodyLimit = 5
)
//noinspection ALL
const (
jsonIndent = " "
jsonIndentPrefix = ""
)
type (
WebConfig struct {
Port int `yaml:"port" json:"port" validate:"min=1,max=65535"`
StaticPathPrefix string `yaml:"staticPathPrefix" json:"staticPathPrefix"`
StaticRootDir string `yaml:"staticRootDir" json:"staticRootDir"`
DirectoryBrowsing bool `yaml:"directoryBrowsing" json:"directoryBrowsing"`
Debug bool `yaml:"debug" json:"debug"`
BodyLimit int `yaml:"bodyLimit" json:"bodyLimit"`
ErrHandler ErrorHandler `json:"-" yaml:"-"`
}
ErrorHandler func(error, Context)
)
var WebDefaultConfig = WebConfig{
Port: DefaultHttpPort,
StaticRootDir: DefaultStaticRoot,
DirectoryBrowsing: false,
Debug: false,
BodyLimit: DefaultWebBodyLimit,
}
type WebX struct {
conf WebConfig
*echo.Echo
ctxPool *sync.Pool
preUseMiddleware middlewares
}
func (this *WebX) grabCtx() *contextImpl {
ctxImpl := this.ctxPool.Get().(*contextImpl)
return ctxImpl
}
func (this *WebX) releaseCtx(ctx *contextImpl) {
std.Assert(ctx != nil, "return ctx is nil")
this.ctxPool.Put(ctx)
}
func (this *WebX) PreUse(m ...MiddlewareFunc) {
this.preUseMiddleware.Use(m...)
}
func NewWeb() *WebX {
return NewWebWithConf(WebDefaultConfig)
}
func (this *WebX) NewContext(r *http.Request, w http.ResponseWriter) Context {
return &contextImpl{
Context: this.Echo.NewContext(r, w),
code: http.StatusOK,
}
}
func NewWebWithConf(conf WebConfig) *WebX {
web := &WebX{
conf: conf,
Echo: echo.New(),
ctxPool: &sync.Pool{
New: func() interface{} {
return new(contextImpl)
},
},
}
web.Use(middleware.Recover())
web.Use(middleware.RequestID())
web.Use(web.customContextMiddleware)
//允许跨域
web.Use(middleware.CORS())
//启用gzip
web.Use(middleware.Gzip())
if conf.Debug {
web.Debug = true
//web.Use(middleware.Logger())
}
//限制body大小
if conf.BodyLimit > 0 {
web.Use(middleware.BodyLimit(fmt.Sprintf("%dM", conf.BodyLimit)))
}
//static
conf.StaticRootDir = strings.Trim(conf.StaticRootDir, " ")
conf.StaticPathPrefix = strings.Trim(conf.StaticPathPrefix, " ")
if conf.StaticRootDir != "" {
err := os.MkdirAll(conf.StaticRootDir, os.ModePerm)
std.AssertError(err, "create web static dir failed")
staticConfig := middleware.StaticConfig{
Root: conf.StaticRootDir,
HTML5: true,
Browse: conf.DirectoryBrowsing,
}
if conf.StaticPathPrefix != "" {
g := web.Group(conf.StaticPathPrefix)
g.Use(middleware.StaticWithConfig(staticConfig))
} else {
web.Use(middleware.StaticWithConfig(staticConfig))
}
}
web.Validator = NewWebValidator()
web.Binder = NewCustomBinder()
web.HideBanner = true
//gWebX.HidePort = true
//统一异常处理
if conf.ErrHandler == nil {
conf.ErrHandler = web.defaultErrorHandler
}
web.HTTPErrorHandler = func(e error, echoCtx echo.Context) {
ctx := web.grabCtx()
defer func() {
ctx.reset()
web.releaseCtx(ctx)
}()
ctx.init(echoCtx)
conf.ErrHandler(e, ctx)
}
return web
}
var webOnce = sync.Once{}
var gWebX *WebX = nil
func Web() *WebX {
std.Assert(gWebX != nil, "web not init yet")
return gWebX
}
func webInit() {
webInitWithConfig(WebDefaultConfig)
}
func webInitWithConfig(conf WebConfig) {
if conf.BodyLimit <= 0 {
conf.BodyLimit = DefaultWebBodyLimit
}
webOnce.Do(func() {
err := std.ValidateStruct(conf)
std.AssertError(err, "web配置不正确")
logger.Printf("web(port=%d,debug=%v) init ...", conf.Port, conf.Debug)
gWebX = NewWebWithConf(conf)
})
}
func (this *WebX) start() {
go func() {
addr := fmt.Sprintf(":%d", this.conf.Port)
if err := this.Start(addr); err != nil {
logger.Println("Web got error when shutting down : ", err)
}
}()
}
func (this *WebX) stop() {
if err := this.Close(); err != nil {
logger.Println(" got error when shutting down: ", err)
}
}