ZBLOG

golang GRPC client get status code from response

In order to get the status code from a gRPC response in Go, you can use the status.Code method from the google.golang.org/grpc/status package.

Here’s an example:

import (
    "google.golang.org/grpc"
    "google.golang.org/grpc/status"
)

func main() {
    // Create a gRPC client connection
    conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
    if err != nil {
        log.Fatalf("Failed to connect to server: %v", err)
    }
    defer conn.Close()

    // Create a gRPC client
    client := pb.NewMyServiceClient(conn)

    // Make a gRPC request
    resp, err := client.MyMethod(context.Background(), &pb.MyRequest{})
    if err != nil {
        s, ok := status.FromError(err)
        if ok {
            fmt.Println(s.Code()) // prints the status code of the response
        }
    }
}

In this example, we’re calling the status.FromError function to extract the gRPC status from the error returned by the MyMethod call. Then we’re using the Code method to get the actual status code value.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=701

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?