-
Notifications
You must be signed in to change notification settings - Fork 1
中间件处理链
starjiang edited this page Jul 22, 2020
·
6 revisions
中间件处理链 可以在微服务接口函数之前,添加自定义middleware 函数链,来解决登录校验,性能统计,日志等问题,具体可以看下面的列子
package main
import (
"flag"
"github.com/starjiang/easycall"
"github.com/starjiang/elog"
)
type ProfileService struct {
}
func (ps *ProfileService) GetProfile(req *easycall.Request, resp *easycall.Response) {
user := &UserInfo{}
req.GetBody(user)
//elog.Infof("head=%v,body=%v", req.GetHead(), user)
respBody := make(map[string]interface{})
respBody["name"] = "jiangyouxing"
respBody["email"] = "[email protected]"
resp.SetHead(req.GetHead()).SetBody(respBody)
}
/**
req 请求包
resp 返回包
client 连接
next 下一个处理middleware
*/
func Middleware1(req *easycall.Request, resp *easycall.Response, client *easycall.EasyConnection, next *easycall.MiddlewareInfo) {
user := &UserInfo{}
req.GetBody(user)
elog.Infof("head1=%v,body1=%v", req.GetHead(), user)
next.Middleware(req, resp, client, next.Next)
}
func Middleware2(req *easycall.Request, resp *easycall.Response, client *easycall.EasyConnection, next *easycall.MiddlewareInfo) {
user := &UserInfo{}
req.GetBody(user)
elog.Infof("head2=%v,body2=%v", req.GetHead(), user)
// resp.SetHead(req.GetHead()).SetBody(make(map[string]interface{}))
// respPkg := easycall.NewPackageWithBody(resp.GetFormat(), resp.GetHead(), resp.GetBody())
// pkgData, err := respPkg.EncodeWithBody()
// if err != nil {
// elog.Error("encode pkg fail:", err)
// }
// client.Send(pkgData)
// 此处拦截请求并回包
next.Middleware(req, resp, client, next.Next)
}
type UserInfo struct {
Name string `json:"name"`
Uid uint64 `json:"uid"`
Seq uint64 `json:"seq"`
}
var port int
func init() {
flag.IntVar(&port, "port", 8001, "listen port")
}
type ApmReport struct {
service string
}
func (ar *ApmReport) OnData(data map[string]*easycall.ApmMonitorStatus) {
elog.Error(data["GetProfile"])
}
func main() {
flag.Parse()
defer elog.Flush()
context := easycall.NewServiceContext([]string{"127.0.0.1:2379"})
context.CreateService("profile", port, &ProfileService{}, 100)
context.AddMiddleware("profile", Middleware1) //添加处理中间件函数Middleware1
context.AddMiddleware("profile", Middleware2)//添加处理中间件函数Middleware2
context.AddMiddleware("profile", easycall.NewApmMonitor(&ApmReport{"profile"}).Middleware) //添加Apm 中间件,统计接口性能
//以上添加了三个middleware 函数,执行顺序按照添加顺序
context.StartAndWait()
}