
protoc-gen-go-flags 现已开源,欢迎大家 Star https://github.com/kunstack/protoc-gen-go-flags
protoc-gen-go-flags 插件主要逻辑:
.proto 消息结构pflag 类型AddFlags 方法的 .flags.go 文件下面是一个简单的的示例:
syntax = "proto3"; package config; import "flags/annotations.proto"; option go_package = "github.com/example/config;config"; message Server { // 允许为空消息生成 AddFlags 方法 option (flags.allow_empty) = true; string host = 1 [(flags.value).string = { name: "host" short: "H" usage: "Server host address" default: "localhost" }]; int32 port = 2 [(flags.value).int32 = { name: "port" short: "p" usage: "Server port number" default: 8080 }]; bool debug = 3 [(flags.value).bool = { name: "debug" short: "d" usage: "Enable debug mode" }]; } 在命令行中执行生成指令:
protoc -I. \ --go_out=. --go_opt=paths=source_relative \ --flags_out=. --flags_opt=paths=source_relative \ config.proto 生成的代码能够无缝集成到 Cobra 或标准 pflag 中:
package main import ( "fmt" "os" "github.com/spf13/pflag" pb "github.com/example/config" ) func main() { cfg := &pb.Server{} // 设置默认值(可选但推荐) cfg.SetDefaults() // 创建独立的 FlagSet ,避免污染全局标志 fs := pflag.NewFlagSet("server", pflag.ExitOnError) // 核心魔法:一行代码完成所有 Flag 的注册 // 自动生成: --host, --port, --debug cfg.AddFlags(fs) // 解析命令行参数 if err := fs.Parse(os.Args[1:]); err != nil { fmt.Fprintf(os.Stderr, "Error parsing flags: %v\n", err) os.Exit(1) } fmt.Printf("Server starting at %s:%d (Debug: %v)\n", cfg.Host, cfg.Port, cfg.Debug) } 使用示例如下:
./app --host=127.0.0.1 --port=8080 --debug 高级用法可以参考下文档 https://github.com/kunstack/protoc-gen-go-flags/tree/main/examples