登录
首页 >  Golang >  Go问答

描述 proto 文件的正确方法是什么?

来源:stackoverflow

时间:2024-03-24 23:18:32 121浏览 收藏

创建 proto 文件时,要匹配数据库表的结构,需要考虑 proto3 中没有必填和可选字段选项的情况。此外,指定字段默认值的方法也与数据库语法不同。文章提供了 city.proto 文件的示例,它使用 Google Protobuf 库中的类型定义字段,并使用 gorm 包进行自动迁移。然而,使用 protoc 命令生成 Go 代码时遇到了错误,表明插件不受支持。解决方案是等待 gRPC 团队提供支持或使用 Google Protobuf V1.20.0 和 protobuf/grpc Go 代码,但后者会生成使用 ProtoReflect 方法的新反射 API。

问题内容

假设我们将来要创建这样的表:

create table city (
    city_id int8 unique not null,
    foundation_date timestamptz not null default now(),
    city_name varchar null,
    city_type varchar default 'unknown',
    invisible bool null
);

我正在尝试创建一个 proto 文件,该文件将与此表结构匹配且不冲突。但不幸的是,我很困惑并且需要一些帮助。我从官方文档中发现,proto3没有在message中指定必填和可选字段的选项。我也不知道如何在字段中指定默认值。

此时我已经描述了以下 city.proto 文件:

syntax = "proto3";

import "google/protobuf/timestamp.proto";
import "google/protobuf/wrappers.proto";

message city {
    google.protobuf.uint64value city_id = 1;
    google.protobuf.timestamp foundation_date = 1;
    google.protobuf.stringvalue city_name = 3;
    google.protobuf.stringvalue city_type = 4;
    google.protobuf.boolvalue invisible = 5;
}

通过protoc编译器生成go代码后,我们通常会得到一个强类型的struct。在gorm包的帮助下,我想进行自动迁移并基于此结构创建一个表。

在我的项目中,我使用 go 模块

我使用这样的命令来生成go代码:

protoc proto/city.proto -i. -i%gopath%/src --go_out=plugins=grpc:proto/city

不幸的是,该命令导致以下错误:

--go_out: protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate grpc

go版本

go version go1.12.9 windows/amd64

协议--版本

libprotoc 3.11.4

问题

如何正确描述我们表的proto文件以及如何正确生成go代码?


解决方案


看来我们需要等待 gRPC 人员提供它。发行说明 (https://github.com/protocolbuffers/protobuf-go/releases/tag/v1.20.0#v1.20-grpc-support) 中指出它不受支持。

但我一直在使用 https://github.com/golang/protobuf/releases/tag/v1.4.0-rc.2 和这个新的 google.goolang.org/protobuf V1.20.0 。它生成一个 protobuf/grpc Go 代码,用于实现例如ProtoReflect 方法并实际使用这个新的反射 API。

终于介绍完啦!小伙伴们,这篇关于《描述 proto 文件的正确方法是什么?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>