protobuf组织结构
此处以一个项目talkischeap为例。
运行程序时,一般在talkischeap目录下运行。
基本文件目录结构:
talkischeap
-| proto
-| addressboook.proto
-| google
-| protobuf
-| timestd.proto
具体代码:
addressbook.proto代码:
// [START declaration]
syntax = "proto3";
package tutorial; //注意包名是tutorial
option go_package = "proto/tutorialtb"; //注意指定生成的go程序的包是package tutorialtb。和文件名无关,文件名是proto文件的相对名称。
import "google/protobuf/timestd.proto";
// 注意导入了相对位置在google/protobuf目录下的timestd.proto.
message Person {
string name = 1;
int32 id = 2; // Unique ID number for this person.
string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
string number = 1;
PhoneType type = 2;
}
repeated PhoneNumber phones = 4;
google.protobuf.Timestamp last_updated = 5;
//注意此处,引用的是google.protobuf包下的Timstamp,在timestd.proto包中。
}
// Our address book file is just one of these.
message AddressBook {
repeated Person people = 1;
}
// [END messages]
timestd.proto中的代码
syntax = "proto3";
package google.protobuf; //注意包名是google.protobuf.
option go_package = "proto/tutorialpb/timestamp";
//注意指定生成的go程序的包是package timestamp。和文件名无关,文件名是proto文件的相对名称。
message Timestamp {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
int64 seconds = 1;
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive.
int32 nanos = 2;
}
最终生成的目录结构如下:
talkischeap
-| proto
-| addressboook.proto
-| tutorialpb
-| timestamp
-| tiemstd.pb.go
-| tutorialtb
-| addressbook.pb.go
-| google
-| protobuf
-| timestd.proto