Files
ginrpc/middleware.go
谢小军 aa50d1f68c add middleware
支持调用中间件
2020-06-01 20:06:15 +08:00

65 lines
1.6 KiB
Go

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