You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/internal/api_to_rpc/api.go

60 lines
2.0 KiB

package common
import (
2 years ago
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/trace_log"
2 years ago
"Open_IM/pkg/getcdv3"
2 years ago
utils2 "Open_IM/pkg/utils"
2 years ago
"context"
2 years ago
"fmt"
"github.com/gin-gonic/gin"
"reflect"
)
2 years ago
func ApiToRpc(c *gin.Context, apiReq, apiResp interface{}, rpcName string, rpcClientFunc interface{}, rpcFuncName string) {
2 years ago
if rpcName == "" {
rpcName = utils2.GetFuncName(1)
}
2 years ago
logFuncName := fmt.Sprintf("[ApiToRpc: %s]%s", utils2.GetFuncName(1), rpcFuncName)
2 years ago
ctx := trace_log.NewCtx1(c, rpcFuncName)
defer log.ShowLog(ctx)
if err := c.BindJSON(apiReq); err != nil {
2 years ago
trace_log.WriteErrorResponse(ctx, "BindJSON", err)
return
}
2 years ago
trace_log.SetCtxInfo(ctx, logFuncName, nil, "apiReq", apiReq)
etcdConn, err := getcdv3.GetConn(ctx, rpcName)
if err != nil {
2 years ago
trace_log.WriteErrorResponse(ctx, "GetConn", err)
return
}
2 years ago
rpcClient := reflect.ValueOf(rpcClientFunc).Call([]reflect.Value{
reflect.ValueOf(etcdConn),
2 years ago
})[0].MethodByName(rpcFuncName) // rpcClient func
rpcReqPtr := reflect.New(rpcClient.Type().In(1).Elem()) // *req
2 years ago
CopyAny(apiReq, rpcReqPtr.Interface())
2 years ago
trace_log.SetCtxInfo(ctx, logFuncName, nil, "opUserID", c.GetString("opUserID"), "callRpcReq", rpcString(rpcReqPtr.Elem().Interface()))
respArr := rpcClient.Call([]reflect.Value{
reflect.ValueOf(context.Context(c)), // context.Context (ctx operationID. opUserID)
rpcReqPtr, // rpcClient apiReq
}) // respArr => (apiResp, error)
2 years ago
if !respArr[1].IsNil() { // rpcClient err != nil
err := respArr[1].Interface().(error)
2 years ago
trace_log.WriteErrorResponse(ctx, rpcFuncName, err, "callRpcResp", "error")
return
}
rpcResp := respArr[0].Elem()
2 years ago
trace_log.SetCtxInfo(ctx, rpcFuncName, nil, "callRpcResp", rpcString(rpcResp.Interface()))
if apiResp != nil {
2 years ago
CopyAny(rpcResp.Interface(), apiResp)
}
2 years ago
trace_log.SetSuccess(ctx, rpcFuncName, apiResp)
}
2 years ago
2 years ago
func rpcString(v interface{}) string {
if s, ok := v.(interface{ String() string }); ok {
return s.String()
}
return fmt.Sprintf("%+v", v)
}