【问题标题】:go protobuf: Cannot find package "." in github.com/gogo/protobuf/proto and m.TimeStamp.MarshalToSizedBuffer undefinedgo protobuf:找不到包“。”在 github.com/gogo/protobuf/proto 和 m.TimeStamp.MarshalToSizedBuffer 中未定义
【发布时间】:2022-02-15 16:36:57
【问题描述】:

根据标题提出问题。 尝试用 gogoproto 和 golangprotobuf 两种方式编译。

为两者编写测试,但两者都不会编组。

msg.proto

syntax = "proto3";

import "google/protobuf/timestamp.proto";

package msg;

message Message {
    string Name = 1;
    google.protobuf.Timestamp TimeStamp = 2;
}

demo_test.go

package msg

import (
    "testing"
    "time"

    // gogo "github.com/gogo/protobuf/proto"
    "github.com/golang/protobuf/proto"
    "github.com/golang/protobuf/ptypes/timestamp"
)

var msg = Message{
    Name:      "demo",
    TimeStamp: &timestamp.Timestamp{Seconds: int64(time.Now().Second())},
}

//func TestGogoMessage_Marshal(t *testing.T) {
//  myBytes, err := gogo.Marshal(&msg)
//  if err != nil {
//      t.Fail()
//  }

//  _ = myBytes
//}

func TestProtoMessage_Marshal(t *testing.T) {
    myBytes, err := proto.Marshal(&msg)
    if err != nil {
        t.Fail()
    }

    _ = myBytes
}

编译:

protoc --gofast_out=. ./demo/msg.proto 有效,但运行测试:

# github.com/.../demo
package github.com/.../demo (test)
    imports github.com/gogo/protobuf/proto: cannot find package "." in:
    /Users/.../vendor/github.com/gogo/protobuf/proto

protoc --go_out=. ./demo/msg.proto 有效,但运行测试:

# github.com/.../demo [github.com/.../demo.test]
./msg.pb.go:127:28: m.TimeStamp.MarshalToSizedBuffer undefined (type *timestamp.Timestamp has no field or method MarshalToSizedBuffer)
./msg.pb.go:169:18: m.TimeStamp.Size undefined (type *timestamp.Timestamp has no field or method Size)
./msg.pb.go:277:25: m.TimeStamp.Unmarshal undefined (type *timestamp.Timestamp has no field or method Unmarshal)

【问题讨论】:

    标签: go protocol-buffers protoc


    【解决方案1】:

    这两个命令对我来说都很好,所以,可能问题出在你的环境中。

    关于undefine 错误,看起来您正在使用来自github.com/golang/protobuf/ptypes/timestampTimestamp 结构,它与来自https://github.com/gogo/protobuf/blob/master/types/timestamp.pb.goTimestamp 具有不同的接口。因此,如果您使用protoc --gofast_out=. ./demo/msg.proto 生成msg.pb.go,您将收到此错误。

    【讨论】:

    • protoc 编译正常,问题是当我尝试运行测试时
    • @Gravy 是的,这就是我的意思。 protoc --gofast_out=. ./demo/msg.proto 生成 msg.pb.go,它期望来自 gogo 的 Timestamp,但你使用来自 golang/protobuf 的 Timestamp
    【解决方案2】:

    添加更多选项:

    protoc -I xxx --gogofaster_out=plugins=grpc,paths=source_relative,Mgoogle/protobuf/any.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types:${PB_DIR} xxx.proto
    

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多