forked from devfeel/dotweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
88 lines (75 loc) · 1.89 KB
/
middleware.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
package dotweb
import (
"github.com/devfeel/dotweb/framework/convert"
"github.com/devfeel/dotweb/logger"
"time"
)
// Middleware middleware interface
type Middleware interface {
Handle(ctx *HttpContext) error
SetNext(m Middleware)
Next(ctx *HttpContext) error
}
//middleware 基础类,应用可基于此实现完整Moddleware
type BaseMiddlware struct {
next Middleware
}
func (bm *BaseMiddlware) SetNext(m Middleware) {
bm.next = m
}
func (bm *BaseMiddlware) Next(ctx *HttpContext) error {
return bm.next.Handle(ctx)
}
type xMiddleware struct {
BaseMiddlware
IsEnd bool
}
func (x *xMiddleware) Handle(ctx *HttpContext) error {
if x.IsEnd {
ctx.handle(ctx)
return nil
} else {
if x.next == nil {
if len(ctx.RouterNode.Middlewares()) <= 0 {
ctx.handle(ctx)
} else {
ctx.RouterNode.Use(&xMiddleware{IsEnd: true})
ctx.RouterNode.Middlewares()[0].Handle(ctx)
}
return nil
} else {
return x.Next(ctx)
}
}
}
//请求日志中间件
type RequestLogMiddleware struct {
BaseMiddlware
}
func (m *RequestLogMiddleware) Handle(ctx *HttpContext) error {
m.Next(ctx)
timetaken := int64(time.Now().Sub(ctx.startTime) / time.Millisecond)
log := ctx.Url() + " " + logContext(ctx, timetaken)
logger.Logger().Log(log, LogTarget_HttpRequest, LogLevel_Debug)
return nil
}
//get default log string
func logContext(ctx *HttpContext, timetaken int64) string {
var reqbytelen, resbytelen, method, proto, status, userip string
if ctx != nil {
reqbytelen = convert.Int642String(ctx.Request.ContentLength)
resbytelen = convert.Int642String(ctx.Response.Size)
method = ctx.Request.Method
proto = ctx.Request.Proto
status = convert.Int2String(ctx.Response.Status)
userip = ctx.RemoteIP()
}
log := method + " "
log += userip + " "
log += proto + " "
log += status + " "
log += reqbytelen + " "
log += resbytelen + " "
log += convert.Int642String(timetaken)
return log
}