-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpcontext.go
371 lines (317 loc) · 8.03 KB
/
httpcontext.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
package xweb
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"runtime/pprof"
"sort"
"time"
"github.com/graphql-go/handler"
"github.com/cxuhua/xweb/logging"
"github.com/cxuhua/xweb/martini"
)
var (
m = NewHttpContext()
LoggerFormat = logging.MustStringFormatter(`%{time} %{level:.5s} %{message}`)
LoggerPrefix = ""
HttpTimeout = time.Second * 30
)
func UseFileSystem(dir string, fs http.FileSystem, staticOpt ...martini.StaticOptions) {
m = NewHttpContextWithFS(dir, fs, staticOpt...)
}
func AddExtType(ext string, typ string) {
_ = mime.AddExtensionType(ext, typ)
}
func GraphQL(path string, conf *handler.Config) {
hh := handler.New(conf)
m.Any(path, func(w http.ResponseWriter, r *http.Request) {
hh.ServeHTTP(w, r)
})
}
func Group(path string, fn func(martini.Router), handler ...martini.Handler) {
m.Group(path, fn, handler...)
}
func Get(path string, handler ...martini.Handler) martini.Route {
return m.Get(path, handler...)
}
func NotFound(handler ...martini.Handler) {
m.NotFound(handler...)
}
func Patch(path string, handler ...martini.Handler) martini.Route {
return m.Patch(path, handler...)
}
func Post(path string, handler ...martini.Handler) martini.Route {
return m.Post(path, handler...)
}
func Put(path string, handler ...martini.Handler) martini.Route {
return m.Put(path, handler...)
}
func Delete(path string, handler ...martini.Handler) martini.Route {
return m.Delete(path, handler...)
}
func Options(path string, handler ...martini.Handler) martini.Route {
return m.Options(path, handler...)
}
func Head(path string, handler ...martini.Handler) martini.Route {
return m.Head(path, handler...)
}
func Any(path string, handler ...martini.Handler) martini.Route {
return m.Any(path, handler...)
}
func InitLogger(w io.Writer) {
m.InitDefaultLogger(w)
}
func ServeHTTP(res http.ResponseWriter, req *http.Request) {
m.ServeHTTP(res, req)
}
func SetValidationFunc(name string, vf ValidationFunc) error {
return m.Validator.SetValidationFunc(name, vf)
}
func Validate(v IArgs) error {
return m.Validator.Validate(v)
}
func SetEnv(env string) {
martini.Env = env
}
func Map(v interface{}) {
m.Map(v)
}
func GetBody(req *http.Request) ([]byte, error) {
return m.GetBody(req)
}
func MapTo(v interface{}, t interface{}) {
m.MapTo(v, t)
}
func UseDispatcher(c IDispatcher, in ...martini.Handler) {
m.UseDispatcher(c, in...)
}
func Use(h martini.Handler) {
m.Use(h)
}
func UseRender(opts ...RenderOptions) {
m.UseRender(opts...)
}
func Serve(addr string) error {
return m.ListenAndServe(addr)
}
func Shutdown() {
m.Shutdown()
}
func ListenAndServe(addr string) error {
return m.ListenAndServe(addr)
}
func ServeTLS(addr string, cert, key string) error {
return m.ListenAndServeTLS(addr, cert, key)
}
func ListenAndServeTLS(addr string, cert, key string) error {
return m.ListenAndServeTLS(addr, cert, key)
}
func Logger() *logging.Logger {
return m.GetLogger()
}
type URLS struct {
Method string
Pattern string
View string
Render string
Args IArgs
}
type HttpContext struct {
martini.ClassicMartini
Validator *Validator
URLS []URLS
heapPPROFFiles []string
cpuPPROFFiles []string
http *http.Server
}
func (this *HttpContext) InitDefaultLogger(w io.Writer) {
lw := logging.NewLogBackend(w, LoggerPrefix, 0)
backend := logging.NewBackendFormatter(lw, LoggerFormat)
logging.SetBackend(backend)
}
func (this *HttpContext) UseRender(opts ...RenderOptions) {
this.Use(Renderer(opts...))
}
func (this *HttpContext) SetValidationFunc(name string, vf ValidationFunc) error {
return this.Validator.SetValidationFunc(name, vf)
}
func (this *HttpContext) Validate(v IArgs) error {
if !v.IsValidate() {
return nil
}
return this.Validator.Validate(v)
}
func (this *HttpContext) Logger() *logging.Logger {
return this.GetLogger()
}
func (this *HttpContext) startCPUPprof() (*os.File, string) {
file := fmt.Sprintf("cpu-%s.prof", time.Now().Format("20060102150405"))
log.Println("create cpu prof ", file)
cpuFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(cpuFile)
return cpuFile, file
}
func (this *HttpContext) writeHeapPprof() {
for {
select {
case <-time.After(time.Minute * 10):
file := fmt.Sprintf("heap-%s.prof", time.Now().Format("20060102150405"))
f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(f)
f.Close()
this.heapPPROFFiles = append(this.heapPPROFFiles, file)
if len(this.heapPPROFFiles) > 10 {
os.Remove(this.heapPPROFFiles[0])
this.heapPPROFFiles = this.heapPPROFFiles[1:]
}
log.Println("create heap prof ", file)
}
}
}
func (this *HttpContext) writeCPUPprof() {
cpuFile, file := this.startCPUPprof()
for {
select {
case <-time.After(time.Minute * 30):
pprof.StopCPUProfile()
cpuFile.Close()
this.cpuPPROFFiles = append(this.cpuPPROFFiles, file)
if len(this.cpuPPROFFiles) > 10 {
os.Remove(this.cpuPPROFFiles[0])
this.cpuPPROFFiles = this.cpuPPROFFiles[1:]
}
cpuFile, file = this.startCPUPprof()
}
}
}
func (this *HttpContext) Shutdown() {
if this.http == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
_ = this.http.Shutdown(ctx)
}
func (this *HttpContext) ListenAndServe(addr string) error {
this.PrintURLS()
this.Logger().Infof("http listening on %s (%s)\n", addr, martini.Env)
this.http = &http.Server{
Addr: addr,
Handler: this,
}
return this.http.ListenAndServe()
}
func (this *HttpContext) ListenAndServeTLS(addr string, cert, key string) error {
this.PrintURLS()
this.Logger().Infof("https listening on %s (%s)\n", addr, martini.Env)
this.http = &http.Server{
Addr: addr,
Handler: this,
}
return this.http.ListenAndServeTLS(cert, key)
}
func (this *HttpContext) PrintURLS() {
logv := this.GetLogger()
sort.Slice(this.URLS, func(i, j int) bool {
return this.URLS[i].Pattern < this.URLS[j].Pattern
})
mc, pc, vc, rc := 0, 0, 0, 0
for _, u := range this.URLS {
if len(u.Method) > mc {
mc = len(u.Method)
}
if len(u.Pattern) > pc {
pc = len(u.Pattern)
}
if len(u.View) > vc {
vc = len(u.View)
}
if u.Render == "" {
u.Render = RenderToString(u.Args.Model().Render())
}
if len(u.Render) > rc {
rc = len(u.Render)
}
}
fs := fmt.Sprintf("+ %%-%ds %%-%ds %%-%ds %%-%ds\n", mc, pc, vc, rc)
for _, u := range this.URLS {
logv.Infof(fs, u.Method, u.Pattern, u.View, u.Render)
}
}
var (
staticFS http.FileSystem = nil
)
//是否存在静态缓存文件
func HasStaticFile(path string) bool {
file, err := OpenStaticFile(path)
if err != nil {
return false
}
defer file.Close()
fs, err := file.Stat()
if err != nil {
return false
}
return fs.Size() > 0
}
// 读取镜头文件数据,如果存在staticFS 从这里读取
func OpenStaticFile(path string) (http.File, error) {
if staticFS != nil {
return staticFS.Open(path)
}
return os.Open(path)
}
// 读取镜头文件数据,如果存在staticFS 从这里读取
func ReadStaticFile(path string) ([]byte, error) {
if staticFS != nil {
file, err := staticFS.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return io.ReadAll(file)
}
return ioutil.ReadFile(path)
}
func NewHttpContextWithFS(dir string, fs http.FileSystem, staticOpt ...martini.StaticOptions) *HttpContext {
staticFS = fs
h := &HttpContext{}
r := martini.NewRouter()
m := martini.New()
m.Use(martini.Logger())
m.Use(martini.Recovery())
m.Use(martini.StaticFS(dir, staticFS, staticOpt...))
m.MapTo(r, (*martini.Routes)(nil))
m.Action(r.Handle)
h.Validator = NewValidator()
h.URLS = []URLS{}
h.Martini = m
h.Router = r
return h
}
func NewHttpContext(fs ...http.FileSystem) *HttpContext {
h := &HttpContext{}
r := martini.NewRouter()
m := martini.New()
m.Use(martini.Logger())
m.Use(martini.Recovery())
m.Use(martini.Static("public"))
m.MapTo(r, (*martini.Routes)(nil))
m.Action(r.Handle)
h.Validator = NewValidator()
h.URLS = []URLS{}
h.Martini = m
h.Router = r
return h
}