grpc 实现统一格式的body响应
发布于 2022-10-22 17:07:20阅读 1315
我们写rest api时,统一响应大多是这样的
{
"err": 0,
"msg": "参数错误",//有错误时非空
"data" : {//没错误时才存在
...
}
}
在grpc项目中有些许差异
func Admin2Resetpasswd(ctx context.Context, in *pb.Admin2ResetpasswdRequest) (*pb.Admin2ResetpasswdResponse, error) {
if in.AdminId == in.ToAid {
return nil, status.Error(codes.FailedPrecondition, "不能操作自己账号")
...
grpc有十多种状态编码
`"OK"`: OK,
`"CANCELLED"`:/* [sic] */ Canceled,
`"UNKNOWN"`: Unknown,
`"INVALID_ARGUMENT"`: InvalidArgument,
`"DEADLINE_EXCEEDED"`: DeadlineExceeded,
`"NOT_FOUND"`: NotFound,
`"ALREADY_EXISTS"`: AlreadyExists,
`"PERMISSION_DENIED"`: PermissionDenied,
`"RESOURCE_EXHAUSTED"`: ResourceExhausted,
`"FAILED_PRECONDITION"`: FailedPrecondition,
`"ABORTED"`: Aborted,
`"OUT_OF_RANGE"`: OutOfRange,
`"UNIMPLEMENTED"`: Unimplemented,
`"INTERNAL"`: Internal,
`"UNAVAILABLE"`: Unavailable,
`"DATA_LOSS"`: DataLoss,
`"UNAUTHENTICATED"`: Unauthenticated,
客户端解析
ctx, _ := context.WithTimeout(context.Background(), time.Second)
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "tony")})
if err != nil {
errStatus := status.Convert(err)
log.Printf("SayHello return error: code: %d, msg: %s\n", errStatus.Code(), errStatus.Message())
}
log.Printf("Greeting: %s", r.GetMessage())
参考
https://blog.csdn.net/bigwhite20xx/article/details/120499996