Search code examples
goprotocol-buffers

Protobuf: Import known types (like timestamp) from google.golang.org/protobuf


Until now, I was using github.com/golang/protobuf. Today I've received the warning module github.com/golang/protobuf is deprecated: Use the "google.golang.org/protobuf" module instead. So I did, and the transition went smoothly. But my project is still depending on github.com/golang/protobuf, the repo I want to get rid of. The reason is that I'm using known types in .proto files:

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

When I run protoc (v3.12.4) to generate the according Go files, this will be resolved to

import (
    timestamp "github.com/golang/protobuf/ptypes/timestamp"
    wrappers "github.com/golang/protobuf/ptypes/wrappers"
)

, causing the deprecated dependency to be still in use. Not sure whether it matters, but I'm relying on these protoc plugins:

$ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.30.0
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.3.0

, which are the latest as far as I can tell.

Looking for the latest timestamp type, I stumbled upon https://pkg.go.dev/google.golang.org/protobuf/types/known/timestamppb. The url suggests it might belong to the desired google.golang.org/protobuf package, but I don't know how to import it properly. The underlying github repo contains a readme that tells me:

types/known/timestamppb: Package timestamppb is the generated package for google/protobuf/timestamp.proto.

But google/protobuf/timestamp.proto is the import I'm currently using in my .proto file, and I'm still ending up with import timestamp "github.com/golang/protobuf/ptypes/timestamp", which is the deprecated dependency.

I'm a bit lost on how all to figure out all this dependency resolving, and I don't know where to find the missing piece to get rid of github.com/golang/protobuf dependency. Is there any?


Solution

  • It's confusing because Google made a v1 (github.com/golang/protobuf) to v2 (google.golang.org/protobuf) change for Go.

    The README for v2 provides a good synopsis and there was a blog post about this too (that I can no longer find) but see A New Go API for Protocol Buffers.

    This change (to v2) also included new (generated) Go (!) packages for Google's Well-Known Types see Package index.

    A consequence of this changes is that you should update protoc-gen-go and protoc-gen-go-grpc and, while you're at it, update protoc (v3.12.4) is old (July 2020). The new plugins will generate Go stubs that correctly reference the new GWT Go stubs provided by Google.

    The protoc-gen-go release where the API switch occurred is 1.4.0, see the "Overview".

    The proto import references (e.g. google/protobuf/timestamp.proto) have not changed.