Skip to content

Instantly share code, notes, and snippets.

@timostamm
Created March 9, 2023 12:16
Show Gist options
  • Save timostamm/ff358a1b3c06a449ceea7b4200732f81 to your computer and use it in GitHub Desktop.
Save timostamm/ff358a1b3c06a449ceea7b4200732f81 to your computer and use it in GitHub Desktop.
Basic protoc plugin example
version: v1
plugins:
- plugin: test
path: ["go", "run", "protoc-gen-test.go"]
out: gen
default:
buf generate buf.build/bufbuild/eliza
package main
import (
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/pluginpb"
"io"
"os"
)
func main() {
// A plugin is just a program that reads a CodeGeneratorRequest
// from stdin, so let's read from stdin, and parse the request:
stdin, _ := io.ReadAll(os.Stdin)
req := &pluginpb.CodeGeneratorRequest{}
_ = proto.Unmarshal(stdin, req)
// Note that pluginpb is just a precompiled version of the plugin
// contract definition google/protobuf/compiler/plugin.proto
// that's provided for convenience.
// A plugin writes a CodeGeneratorResponse to stdout. Let's do
// that here. We're going to generate a file req.json, where we
// simply dump the request, but in human-readable JSON format.
res := &pluginpb.CodeGeneratorResponse{}
res.File = append(res.File, &pluginpb.CodeGeneratorResponse_File{
Name: proto.String("req.json"),
Content: proto.String(protojson.Format(req)),
})
stdout, _ := proto.Marshal(res)
_, _ = os.Stdout.Write(stdout)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment