Compiling with protoc
- Go course
- Advanced
- Lesson 39/68
- 4 min
Learn to generate Go code with protoc.
Compiling with protoc
A .proto file is turned into code by the protoc compiler and two Go plugins: protoc-gen-go generates messages and protoc-gen-go-grpc generates service interfaces.
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
selam.protoOutput: selam.pb.go and selam_grpc.pb.go.
Don't edit generated code
Generated .pb.go files aren't edited by hand; changes go into the .proto and the code is regenerated. To avoid remembering the command, a directive is added to a source file and go generate ./... is run:
//go:generate protoc --go_out=. --go-grpc_out=. selam.protoTools such as Buf also simplify compiling and compatibility checks.
Practice Generated interface
Write a simplified version of the server interface generated by protoc-gen-go-grpc: type SelamlayiciServer interface { Selam(ad string) (string, error) }. Write type sunucu struct{} that satisfies it and check it at compile time with var _ SelamlayiciServer = sunucu{}; then print sunucu{}.Selam("Go").
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type SelamlayiciServer interface {
Selam(ad string) (string, error)
}
type sunucu struct{}
func (sunucu) Selam(ad string) (string, error) { return "Merhaba " + ad, nil }
var _ SelamlayiciServer = sunucu{}
func main() {
fmt.Println(sunucu{}.Selam("Go"))
}Expected output
Merhaba Go <nil>
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which plugin generates the service interfaces (Server/Client)?
- protoc-gen-go-grpc Correct answer
- protoc-gen-go
- go vet
- gofmt
Explanation: protoc-gen-go generates only message types; client and server code come from protoc-gen-go-grpc.
2 Message output
protoc ____=. --go-grpc_out=. selam.proto
protoc --go_out=. --go-grpc_out=. selam.proto
Explanation: --go_out runs the protoc-gen-go plugin and generates message code.
3 Tool and output
| Term | Meaning |
|---|---|
protoc |
.proto compiler |
protoc-gen-go |
selam.pb.go |
protoc-gen-go-grpc |
selam_grpc.pb.go |
go generate |
Runs the directives |