Skip to content

Commit

Permalink
Merge pull request #155 from jehiah/flag_support_155
Browse files Browse the repository at this point in the history
Simpler integration of config and the stdlib flag package
  • Loading branch information
mreiferson committed Aug 24, 2015
2 parents a3aee1d + 55e7ca2 commit 0f97a46
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
31 changes: 31 additions & 0 deletions config_flag.go
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 ""
}
25 changes: 25 additions & 0 deletions config_flag_test.go
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)
}

0 comments on commit 0f97a46

Please sign in to comment.