Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simpler integration of config and the stdlib flag package #155

Merged
merged 1 commit into from
Aug 24, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}