Skip to main content

10 Generate Go Code

So far, we've created a new module, pushed it up to the BSR, interacted with autogenerated documentation, and added a dependency on the module. Next, we'll implement the PetStoreService as a Go application and use other powerful Buf features.

Before we continue, move to the start directory again. If you're coming from the previous step, you can simply run the following command:

$ cd ..

We'll also reset the gen directory so that we generate everything from a clean slate. This is especially relevant since we removed the google/type/datetime.proto definition from the module itself.

$ rm -rf gen

The start directory should look like the following:

start/├── buf.gen.yaml└── petapis    ├── buf.lock    ├──    ├── buf.yaml    └── pet        └── v1            └── pet.proto

10.1 Setup Go#

Install go by visiting this link. If you don't have any experience with Go, that's OK! We'll cover everything you need to know here.

10.2 Install plugins#

We'll be using the protoc-gen-go and protoc-gen-go-grpc plugins to generate code with buf generate, so you'll need to install them:

$ go install$ go install

You will also need to update your PATH so that buf can find the plugins:

$ export PATH="$PATH:$(go env GOPATH)/bin"

10.3 Edit your buf.gen.yaml#

Edit the buf.gen.yaml file so that it configures the protoc-gen-go and protoc-gen-go-grpc plugins (and their options) like so:

 version: v1 plugins:-  - name: cpp-    out: gen/proto/cpp-  - name: java-    out: gen/proto/java+  - name: go+    out: gen/proto/go+    opt: paths=source_relative+  - name: go-grpc+    out: gen/proto/go+    opt:+      - paths=source_relative+      - require_unimplemented_servers=false

In short, these edits can be explained by the following:

  • Execute the protoc-gen-go plugin with the paths=source_relative option, and place its output in the gen/proto/go directory.
  • Execute the protoc-gen-go-grpc plugin with the paths=source_relative and require_unimplemented_servers=false options, and place its output in the gen/proto/go directory.

10.4 Generate Go/gRPC Client and Server Stubs#

Now that you have a buf.gen.yaml with the protoc-gen-go[-grpc] plugins configured, you can generate the code required to implement the PetStoreService API with Go.

Simply run the following command (targeting the version of the module we pushed up to the BSR earlier):

$ buf generate$BUF_USER/petapis

If a --template is not explicitly specified, the buf.gen.yaml found in the current directory is used by default.

If successful, you'll notice a couple new files in the gen/proto/go directory (as configured by the buf.gen.yaml created above):

start/├── buf.gen.yaml├── gen│   └── proto│       └── go│           └── pet│               └── v1│                   ├── pet.pb.go│                   └── pet_grpc.pb.go└── petapis    ├── buf.lock    ├──    ├── buf.yaml    └── pet        └── v1            └── pet.proto