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 *****/ /************************************/