forked from devfeel/dotweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
92 lines (78 loc) · 2.06 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
89
90
91
92
package dotweb
import (
"github.com/devfeel/dotweb/framework/convert"
"github.com/devfeel/dotweb/logger"
"reflect"
"time"
)
type MiddlewareFunc func() Middleware
// Middleware middleware interface
type Middleware interface {
Handle(ctx Context) error
SetNext(m Middleware)
Next(ctx Context) error
}
//middleware 基础类,应用可基于此实现完整Moddleware
type BaseMiddlware struct {
next Middleware
}
func (bm *BaseMiddlware) SetNext(m Middleware) {
bm.next = m
}
func (bm *BaseMiddlware) Next(ctx Context) error {
return bm.next.Handle(ctx)
}
type xMiddleware struct {
BaseMiddlware
IsEnd bool
}
func (x *xMiddleware) Handle(ctx Context) error {
len := len(ctx.RouterNode().Middlewares())
if x.IsEnd {
return ctx.Handler()(ctx)
} else {
if x.next == nil {
if len <= 0 {
return ctx.Handler()(ctx)
} else {
if reflect.TypeOf(ctx.RouterNode().Middlewares()[len-1]).String() != "*dotweb.xMiddleware" {
ctx.RouterNode().Use(&xMiddleware{IsEnd: true})
}
return ctx.RouterNode().Middlewares()[0].Handle(ctx)
}
} else {
return x.Next(ctx)
}
}
}
//请求日志中间件
type RequestLogMiddleware struct {
BaseMiddlware
}
func (m *RequestLogMiddleware) Handle(ctx Context) error {
m.Next(ctx)
timetaken := int64(time.Now().Sub(ctx.(*HttpContext).startTime) / time.Millisecond)
log := ctx.Request().Url() + " " + logContext(ctx, timetaken)
logger.Logger().Log(log, LogTarget_HttpRequest, LogLevel_Debug)
return nil
}
//get default log string
func logContext(ctx Context, 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
}