mirror of
https://github.com/xxjwxc/ginrpc.git
synced 2025-10-05 15:06:56 +08:00
add middleware
支持调用中间件
This commit is contained in:
64
middleware.go
Normal file
64
middleware.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package ginrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/xxjwxc/public/message"
|
||||
|
||||
"github.com/xxjwxc/public/mylog"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GinBeforeAfterInfo 对象调用前后执行中间件参数
|
||||
type GinBeforeAfterInfo struct {
|
||||
C *gin.Context
|
||||
FuncName string // 函数名
|
||||
Req interface{} // 调用前的请求参数
|
||||
Resp interface{} // 调用后的返回参数
|
||||
Error error
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
Context context.Context // 占位参数,可用于存储其他参数,前后连接可用
|
||||
|
||||
}
|
||||
|
||||
// GinBeforeAfter 对象调用前后执行中间件(支持总的跟对象单独添加)
|
||||
type GinBeforeAfter interface {
|
||||
GinBefore(req *GinBeforeAfterInfo) bool
|
||||
GinAfter(req *GinBeforeAfterInfo) bool
|
||||
}
|
||||
|
||||
// DefaultGinBeforeAfter 创建一个默认 BeforeAfter Middleware
|
||||
type DefaultGinBeforeAfter struct {
|
||||
}
|
||||
|
||||
type timeTrace struct{}
|
||||
|
||||
// GinBefore call之前调用
|
||||
func (d *DefaultGinBeforeAfter) GinBefore(req *GinBeforeAfterInfo) bool {
|
||||
req.Context = context.WithValue(req.Context, timeTrace{}, time.Now())
|
||||
return true
|
||||
}
|
||||
|
||||
// GinAfter call之后调用
|
||||
func (d *DefaultGinBeforeAfter) GinAfter(req *GinBeforeAfterInfo) bool {
|
||||
begin := (req.Context.Value(timeTrace{})).(time.Time)
|
||||
now := time.Now()
|
||||
mylog.Info(fmt.Sprintf("[middleware] call[%v] [%v]", req.FuncName, now.Sub(begin)))
|
||||
// 设置resp 结果
|
||||
if req.Error == nil {
|
||||
msg := message.GetSuccessMsg()
|
||||
msg.Data = req.Resp
|
||||
req.Resp = msg
|
||||
} else {
|
||||
msg := message.GetErrorStrMsg(req.Error.Error())
|
||||
msg.Data = req.Resp
|
||||
req.Resp = msg
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ----------------end
|
Reference in New Issue
Block a user