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.