feat 新增消息拦截过滤上下文的复制功能

pull/145/head
ltf 4 years ago
parent f1229be04c
commit 62b76f06c8

@ -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)

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

Loading…
Cancel
Save