-
Notifications
You must be signed in to change notification settings - Fork 442
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #155 from jehiah/flag_support_155
Simpler integration of config and the stdlib flag package
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 "" | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
} |