【发布时间】:2020-05-17 08:50:21
【问题描述】:
在我用 golang 编写的 gRPC 服务中,我有这样的 rpc method 称为 CreateCity。如您所见,在此方法中,我想在数据库中创建一条新记录,并将有关此记录的所有信息作为响应返回。
func (server *Server) CreateCity(context context.Context, request *proto.CreateCityRequest) (*proto.CreateCityResponse, error) {
city := proto.City {
Name: request.GetCity().Name,
Country: request.GetCity().Country,
}
err := databases.DBGORM.Table("city").Create(&city).Error
if err != nil {
utils.Logger().Println(err.Error())
return nil, status.Errorf(codes.Internal, err.Error())
}
result := &proto.CreateCityResponse {
City: &city,
}
return result, nil
}
proto 文件如下所示:
syntax = "proto3";
package proto;
import "google/protobuf/wrappers.proto";
import "google/protobuf/timestamp.proto";
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
option go_package = "./proto";
service CityService {
rpc CreateCity(CreateCityRequest) returns (CreateCityResponse) {}
}
message City {
google.protobuf.StringValue name = 1 [json_name = "name", (gogoproto.jsontag) = "name", (gogoproto.wktpointer) = true];
google.protobuf.StringValue country = 2 [json_name = "country", (gogoproto.jsontag) = "country", (gogoproto.wktpointer) = true];
}
message CreateDealerGroupRequest {
City city = 1;
}
message CreateDealerGroupResponse {
City city = 1;
}
是否可以在不明确指定名称的情况下用数据动态填充结构?正如您现在所看到的,我明确指定了字段的名称及其值:
city := proto.City {
Name: request.GetCity().Name,
Country: request.GetCity().Country,
}
【问题讨论】:
标签: go protocol-buffers grpc proto protoc