From 62b76f06c8547c1bf854ae767b2f979a841b31b0 Mon Sep 17 00:00:00 2001 From: ltf Date: Mon, 28 Feb 2022 16:38:55 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E6=96=B0=E5=A2=9E=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E6=8B=A6=E6=88=AA=E8=BF=87=E6=BB=A4=E4=B8=8A=E4=B8=8B=E6=96=87?= =?UTF-8?q?=E7=9A=84=E5=A4=8D=E5=88=B6=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/rpc/open_im_msg/filters/mock.go | 23 ++++++++++++++++++++++- internal/rpc/msg/context.go | 13 +++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/cmd/rpc/open_im_msg/filters/mock.go b/cmd/rpc/open_im_msg/filters/mock.go index b2b12cd7a..950cf6124 100644 --- a/cmd/rpc/open_im_msg/filters/mock.go +++ b/cmd/rpc/open_im_msg/filters/mock.go @@ -4,11 +4,31 @@ import ( rpcChat "Open_IM/internal/rpc/msg" "Open_IM/pkg/common/constant" pbChat "Open_IM/pkg/proto/chat" + "context" "errors" "fmt" + "time" ) func MockBeforeSendFilter1(ctx *rpcChat.SendContext, pb *pbChat.SendMsgReq) (*pbChat.SendMsgResp, bool, error) { + + cp := ctx.Copy() + + // 假设这里我们发起一次rpc,超时时间 1s + sc, cancel := context.WithTimeout(cp, time.Second*1) + defer cancel() + + sc.Value("ss") // 无意义,只是为了不报错 + + // callRpc(sc,pb) + + // other logic + // doOther() + + // 模拟处理时间 + time.Sleep(2 * time.Second) + + // mock 将一些需要的数据放入ctx,供后续其他拦截过滤器使用 ctxKey := "test_key" v := true // fmt.Printf("MockBeforeSendFilter1:%s set value to ctx,value is :%v\n", ctxKey, v) @@ -19,13 +39,14 @@ func MockBeforeSendFilter1(ctx *rpcChat.SendContext, pb *pbChat.SendMsgReq) (*pb // MockBeforeSendFilter is a mock handle that handles custom logic before send msg. func MockBeforeSendFilter2(ctx *rpcChat.SendContext, pb *pbChat.SendMsgReq) (*pbChat.SendMsgResp, bool, error) { + // 取出放进去的测试数据 ctxKey := "test_key" v, ok := ctx.Value(ctxKey).(bool) if ok { fmt.Printf("MockBeforeSendFilter2:%s selected from ctx,value is :%v\n", ctxKey, v) } - // fmt.Printf("MockBeforeSendHandler trigger,contentType:%d\n", pb.MsgData.GetContentType()) + fmt.Printf("MockBeforeSendFilter2 trigger,contentType:%d\n", pb.MsgData.GetContentType()) if pb.MsgData.ContentType == constant.Text { msg := string(pb.MsgData.Content) // fmt.Printf("text msg:%s\n", msg) diff --git a/internal/rpc/msg/context.go b/internal/rpc/msg/context.go index 0701a9bd8..5206ae347 100644 --- a/internal/rpc/msg/context.go +++ b/internal/rpc/msg/context.go @@ -95,6 +95,19 @@ func (c *SendContext) WithValue(key, val interface{}) { c.SetCtx(ctx) } +// Copy returns a copy of the current context that can be safely used outside the request's scope. +// This has to be used when the context has to be passed to a goroutine or wrapped by WithTimeout etc. +func (c *SendContext) Copy() *SendContext { + cp := SendContext{ + ctx: c.ctx, + rpc: c.rpc, + beforeFilters: c.beforeFilters, + afterSenders: c.afterSenders, + } + + return &cp +} + /************************************/ /***** context *****/ /************************************/