diff --git a/config_flag.go b/config_flag.go new file mode 100644 index 00000000..037da188 --- /dev/null +++ b/config_flag.go @@ -0,0 +1,31 @@ +package nsq + +import ( + "strings" +) + +// ConfigFlag wraps a Config and implements the flag.Value interface +type ConfigFlag struct { + *Config +} + +// Set takes a comma separated value and follows the rules in Config.Set +// using the first field as the option key, and the second (if present) as the value +func (c *ConfigFlag) Set(opt string) (err error) { + parts := strings.SplitN(opt, ",", 2) + key := parts[0] + + switch len(parts) { + case 1: + // default options specified without a value to boolean true + err = c.Config.Set(key, true) + case 2: + err = c.Config.Set(key, parts[1]) + } + return +} + +// String implements the flag.Value interface +func (c *ConfigFlag) String() string { + return "" +} diff --git a/config_flag_test.go b/config_flag_test.go new file mode 100644 index 00000000..399d5a24 --- /dev/null +++ b/config_flag_test.go @@ -0,0 +1,25 @@ +package nsq_test + +import ( + "flag" + + "github.com/bitly/go-nsq" +) + +func ExampleConfigFlag() { + cfg := nsq.NewConfig() + flagSet := flag.NewFlagSet("", flag.ExitOnError) + + flagSet.Var(&nsq.ConfigFlag{cfg}, "consumer.options", "option to passthrough to nsq.Consumer (may be given multiple times, http://godoc.org/github.com/bitly/go-nsq#Config.Set)") + flagSet.PrintDefaults() + + err := flagSet.Parse([]string{ + "-consumer.options=heartbeat_interval,1s", + "-consumer.options=max_attempts,10", + }) + if err != nil { + panic(err.Error()) + } + println("HeartbeatInterval", cfg.HeartbeatInterval) + println("MaxAttempts", cfg.MaxAttempts) +}