package server import ( "context" "joybuywork/internal/app" "joybuywork/internal/config" "joybuywork/internal/consts" "joybuywork/internal/plugins/jsonm" "joybuywork/internal/plugins/printer" "joybuywork/proto/go_proto/workerr" "fmt" "github.com/rs/xid" "go-micro.dev/v4/client" "go-micro.dev/v4/metadata" "go-micro.dev/v4/registry" "go-micro.dev/v4/server" "time" ) func Recover() server.HandlerWrapper { return func(handlerFunc server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) (err error) { defer func() { if r := recover(); r != nil { body, _ := jsonm.Marshal(req.Body()) // 捕获后发送到微信处理 var errMsg string errMsg += "环境:" + config.Config.Server.Env + "\n" errMsg += "请求服务:[" + string(req.Service()) + "]" + req.Endpoint() + "\n" errMsg += "请求rawData:" + body.ToString() + "\n" errMsg += "错误内容:" + fmt.Sprintf("%s", r) app.Logger.ErrorWithStack(ctx, errMsg) err = workerr.ServerError } }() return handlerFunc(ctx, req, rsp) } } } func HandlerWrapper() server.HandlerWrapper { return func(handlerFunc server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) (err error) { start := time.Now() rbody, _ := jsonm.Marshal(req.Body()) sl := printer.NewSlowLog(ctx) uri := fmt.Sprintf("%s/%s", req.Service(), req.Method()) app.Collect(uri) sl.Start(fmt.Sprintf("uri: %s, req: %s", uri, rbody.ToString())) defer func() { body, _ := jsonm.Marshal(rsp) sl.End( fmt.Sprintf("res: %s, err: %v, time: %12v", body.ToString(), err, time.Since(start)), err, uri, rbody.ToString(), body.ToString(), ) }() return handlerFunc(ctx, req, rsp) } } } func TradeWrapper() server.HandlerWrapper { return func(handlerFunc server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { if tradeId, ok := metadata.Get(ctx, consts.TraceIdKey); ok && tradeId != "" { ctx = context.WithValue(ctx, consts.TraceIdKey, tradeId) } else { ctx = context.WithValue(ctx, consts.TraceIdKey, xid.New().String()) } ctx = context.WithValue(ctx, consts.CtxReqId, xid.New().String()) return handlerFunc(ctx, req, rsp) } } } // CallWrapper 中间件 func CallWrapper() client.CallWrapper { return func(callFunc client.CallFunc) client.CallFunc { return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) (err error) { start := time.Now() defer func() { latency := time.Since(start) body, _ := jsonm.Marshal(rsp) printer.Print(ctx, fmt.Sprintf("cres: %s, err: %v, time: %12v", body.ToString(), err, latency), err) }() body, _ := jsonm.Marshal(req.Body()) printer.Print(ctx, fmt.Sprintf("uri: %s_%s, creq: %s", req.Service(), req.Method(), body.ToString()), nil) return callFunc(ctx, node, req, rsp, opts) } } }