【问题标题】:How dynamically fill of the struct with data?如何用数据动态填充结构?
【发布时间】: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


【解决方案1】:

你可以使用json.Marshal创建json字节数组然后json.Unmarshal

inrec, _ := json.Marshal(request.GetCity())
json.Unmarshal(inrec, &city)

【讨论】:

    【解决方案2】:

    我相信你最好的选择是使用反射并遍历源结构的所有字段,将它们与目标结构进行比较,如果它们匹配则分配它们。

    通过谷歌快速搜索发现了这个包:https://github.com/stroiman/go-automapper。 (我自己没用过,这里只是举例)
    您想要的代码在这里:here.
    不想在此答案中包含代码,因为您可能想要更改它 - 但总体思路就在那里。

    就个人而言,如果可行的话,我会采用手动方法(就像您现在所做的那样)。 依赖反射会更慢,但更重要的是,模型的更改可能会以不可预见的方式影响映射。 仅取决于您的用例 imo。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      相关资源
      最近更新 更多