使用带有 GRPC 的 swagger 生成响应示例值

Generate response example values using swagger with GRPC

我正在使用 protoc-gen-swagger 和 gRPC 服务生成 swagger json 文件。生成的输出 json 包含空的响应示例,我想将响应示例添加到定义中,以便它自动填充到生成的 json.

这是我目前的定义。

service UserService {
  rpc GetUser (GetUserRequest) returns (UserResponse){
    option (google.api.http) = {
      get: "/api/v1/user/{username}"
      response_body: "*"
    };
    option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = {
      description: "Returns user object";
      operation_id: "get_user";
      summary: "Get User";
    };
  }
}

message GetUserRequest {
  string username = 1;
}

message UserResponse {
  User user = 1;
}

message User {
  string first_name = 1;
  string last_name = 2;
  string username = 3;
}

当我使用命令生成 swagger 文件时

protoc -I ${PROTOPATH} \
           -I $GOPATH/src \
           --swagger_out=logtostderr=true:${OUT_PATH}

我得到一个包含此用户对象定义的 swagger 文件

"User": {
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "username": {
      "type": "string"
    },
  }
}

我想要的是用这样的示例值生成它:

"User": {
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string",
      "example": "Adam"
    },
    "last_name": {
      "type": "string",
      "example": "Smith"
    },
    "username": {
      "type": "string",
      "example": "asmith79"
    },
  }
}

在这里找到了答案:https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto#L197

只需将 grpc.gateway.protoc_gen_swagger.options.openapiv2_schema 作为选项添加到消息中即可。

import "protoc-gen-swagger/options/annotations.proto";

message User {
  option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = {
    example: { value: '{ "first_name": "Adam", "last_name":"Smith", "username":"asmith79"}' }
  };
  string first_name = 1;
  string last_name = 2;
  string username = 3;
}