Created
March 9, 2023 12:16
-
-
Save timostamm/ff358a1b3c06a449ceea7b4200732f81 to your computer and use it in GitHub Desktop.
Basic protoc plugin example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
version: v1 | |
plugins: | |
- plugin: test | |
path: ["go", "run", "protoc-gen-test.go"] | |
out: gen |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
default: | |
buf generate buf.build/bufbuild/eliza |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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