在gRPC服务器方法调用中设置状态码

huangapple go评论141阅读模式
英文:

Setting status code in grpc server method call

问题

在golang中,你可以使用google.golang.org/grpc/status包来设置grpc方法的响应状态码。以下是一个示例:

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

func (i *ItemServerImp) Register(ct context.Context, it *item.RegisterItemRequest) (*item.RegisterItemReply, error) {
    // 根据输入或某些处理逻辑设置响应状态码
    if someCondition {
        // 设置状态码为200
        return nil, status.Error(codes.OK, "Success")
    } else {
        // 设置状态码为400
        return nil, status.Error(codes.InvalidArgument, "Invalid argument")
    }
}

在上面的示例中,我们使用status.Error函数来创建一个带有指定状态码和错误消息的错误。codes包中定义了一系列常用的状态码,你可以根据需要选择合适的状态码。

英文:

How do I set the response status code in a grpc method in golang. For example lets say I have the following grpc method

func (i *ItemServerImp) Register(ct context.Context, it *item.RegisterItemRequest) (*item.RegisterItemReply, error) {
}

How do I set the response status to 200 or a 400 based on the input or some processing. I had a look around and could not find a proper way to do this.

However I did find the following https://chromium.googlesource.com/external/github.com/grpc/grpc/+/refs/heads/chromium-deps/2016-07-27/doc/statuscodes.md which says the status code can be set.

答案1

得分: 5

你可以使用google.golang.org/grpc/status包来返回一个gRPC错误,示例如下:

return nil, status.Error(codes.InvalidArgument, "Incorrect request argument")

不同的状态码可以在google.golang.org/grpc/codes包中找到。

英文:

You can return a gRPC error using the google.golang.org/grpc/status package as follows:

return nil, status.Error(codes.InvalidArgument, "Incorrect request argument")

The different status codes are available in the google.golang.org/grpc/codes package.

huangapple
  • 本文由 发表于 2021年5月20日 14:17:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/67614912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定