A protoc plugin that lets you extend generated protobuf types with custom Go code using sidecar files — no type aliasing or wrapper structs required.
In Go, you can't add methods to types defined in other packages. If protoc-gen-go generates a User struct in userpb, you're stuck with workarounds like:
// Type definition just to add behavior
type User userpb.User
func (u *User) FullName() string {
return u.FirstName + " " + u.LastName
}This breaks type compatibility and requires casts everywhere the original type is used.
Write a sidecar .proto.ext.go file next to your .proto file:
proto/
user.proto
user.proto.ext.go ← your extensions
gen/
userpb/
user.pb.go ← generated by protoc-gen-go
user_ext.pb.go ← generated by protoc-gen-extend
The sidecar is a plain Go file (with a //go:build ignore tag so go build skips it in place):
//go:build ignore
package userpb
import "strings"
func (m *User) FullName() string {
return strings.TrimSpace(m.FirstName + " " + m.LastName)
}
func NewUser(first, last string) *User {
return &User{FirstName: first, LastName: last}
}protoc-gen-extend picks up the sidecar, validates that all receiver types are messages in the proto file, and emits the code into the generated output package. Methods, constants, constructors, and variables land directly alongside the generated types.
go install github.com/codenaugh/protoc-gen-extend@latestprotoc \
--proto_path=proto \
--go_out=gen \
--go_opt=paths=source_relative \
--extend_out=sidecar_root=proto:gen \
--extend_opt=paths=source_relative \
proto/user.proto| Option | Description |
|---|---|
sidecar_root |
Root directory to search for .proto.ext.go sidecar files. Typically the same as your --proto_path. Required since protoc doesn't expose --proto_path to plugins. |
- Named
<name>.proto.ext.goto match<name>.proto - Must have a
//go:build ignoretag so it's not compiled in place - Package name is rewritten to match the generated output
- Receiver types are validated against messages in the proto file
- Imports are carried through to the generated output
- Supports methods, constants, variables, type declarations, and standalone functions
If a sidecar references a type that isn't a message in the proto file, the plugin fails with a helpful error:
method Bad has receiver *Foo, but Foo is not a message in user.proto
available messages: User, Team
See the example/ directory. Run it with:
make examplemake build # build locally
make test # run tests
make proto # generate example output
make clean # remove artifacts