本文整理汇总了Golang中github.com/rakyll/globalconf.NewWithOptions函数的典型用法代码示例。如果您正苦于以下问题:Golang NewWithOptions函数的具体用法?Golang NewWithOptions怎么用?Golang NewWithOptions使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewWithOptions函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ReadApiConfig
func ReadApiConfig(fileLocation string) (a *ApiConfig) {
f := flag.NewFlagSet("api", flag.ContinueOnError)
flagApiHostname := f.String("api_host", "127.0.0.1", "Api hostname")
flagApiPort := f.Uint("api_port", 8844, "Api port")
globalconf.Register("api", f)
g, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: fileLocation,
})
if err != nil {
log.Printf("[config][warning] Could not parse config file %s"+
" Error: %s, Falling back to default settings",
fileLocation, err.Error())
} else {
g.ParseAll()
}
return &ApiConfig{
Host: *flagApiHostname,
Port: uint16(*flagApiPort),
}
}
示例2: main
func main() {
// Get the configuration
//
if *configFile == "" {
*configFile = "./nightcrawler.ini"
}
opts := globalconf.Options{Filename: *configFile, EnvPrefix: "NC_"}
conf, _ := globalconf.NewWithOptions(&opts)
conf.ParseAll()
// Static assets should be served by nginx in production
//
println(martini.Env)
m := martini.Classic()
if martini.Env != "production" {
m.Use(martini.Static("assets"))
}
// This is just a temp route in development mode
//
if martini.Env == "development" {
m.Get("/", UserRendererMiddleware(), func(r render.Render) {
r.HTML(200, "root", nil)
})
}
// Top level of app
// This section is everything outside of authentication
//
m.Group("/app", func(r martini.Router) {
r.Get("/sign_in", controllers.SignIn)
r.Post("/sign_in", csrf.Validate, controllers.SignIn)
r.Get("/sign_up", controllers.SignUp)
r.Post("/sign_up", csrf.Validate, controllers.CreateSignUp)
r.Get("/sign_out", controllers.SignOut)
r.NotFound(func(x render.Render) {
x.HTML(404, "404", nil)
})
},
CookieStore(*userCookieSecret, *userSessionName),
UserSessionAuth(),
CSRFMiddleware(*userSessionSecret, *userSessionKey),
UserRendererMiddleware(),
)
// Admin interface
m.Group("/app/admin", func(r martini.Router) {
r.Get("/sign_in", controllers.AdminSignIn)
r.NotFound(func(x render.Render) {
x.HTML(404, "404_admin", nil)
})
},
CookieStore("admin123", "nightcrawler_admin"),
AdminSessionAuth(),
CSRFMiddleware("admin123", "adminId"),
AdminRendererMiddleware(),
)
m.Run()
}
示例3: setup
func setup(name string) error {
var (
conf *globalconf.GlobalConf
file string
err error
)
// Check for environment variable override, and return error if override is set but file is
// inaccessible. Otherwise, try for the default global location (in the "/etc" directory).
if file := os.Getenv(strings.ToUpper(name) + "_CONFIG"); file != "" {
if _, err = os.Stat(file); err != nil {
return err
}
} else {
file = "/etc/" + name + "/" + name + ".conf"
if _, err = os.Stat(file); err != nil {
file = ""
}
}
// Load from specific configuration file if set, or use local configuration file as a fallback.
if file != "" {
options := &globalconf.Options{Filename: file, EnvPrefix: ""}
if conf, err = globalconf.NewWithOptions(options); err != nil {
return err
}
} else if conf, err = globalconf.New(name); err != nil {
return err
}
conf.EnvPrefix = strings.ToUpper(name) + "_"
conf.ParseAll()
return nil
}
示例4: ReadDbConfig
func ReadDbConfig(fileLocation string) *DatabaseConfig {
f := flag.NewFlagSet("database", flag.ContinueOnError)
flagDBHostname := f.String("db_host", "127.0.0.1", "Database hostname")
flagDBPort := f.Uint("db_port", 5432, "Database port")
flagDBUsername := f.String("db_username", "ubi", "Database username")
flagDBPassword := f.String("db_password", "password", "Database password")
flagDBName := f.String("db_name", "ubi_course", "Database name")
flagDBSSLMode := f.String("db_sslmode", "disable", "Database SSL mode")
globalconf.Register("database", f)
g, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: fileLocation,
})
if err != nil {
log.Printf("[config][warning] Could not parse config file '%s': %s. "+
"Falling back to default settings",
fileLocation, err.Error())
} else {
g.ParseAll()
}
return &DatabaseConfig{
Hostname: *flagDBHostname,
Port: uint16(*flagDBPort),
Username: *flagDBUsername,
Password: *flagDBPassword,
Name: *flagDBName,
SSLMode: *flagDBSSLMode,
}
}
示例5: ReadDaqConfig
func ReadDaqConfig(fileLocation string) *DaqConfig {
f := flag.NewFlagSet("daq", flag.ContinueOnError)
flagDaqInterval := f.Uint("daq_interval", 5, "Daq interval in minutes")
flagMockerOn := f.Bool("daq_mocker_on", false, "Mocker state")
globalconf.Register("daq", f)
g, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: fileLocation,
})
if err != nil {
log.Printf("[config][warning] Could not parse config file %s"+
" Error: %s, Falling back to default settings",
fileLocation, err.Error())
} else {
g.ParseAll()
}
return &DaqConfig{
Interval: *flagDaqInterval,
MockerOn: *flagMockerOn,
}
}
示例6: parseConf
// parse conf from env and args
func parseConf() {
// let mflag parse first
mflag.Parse()
// using gconf parse env
gconf, err := globalconf.NewWithOptions(&globalconf.Options{
EnvPrefix: "WICKET_",
})
if err != nil {
log.Fatalf("error parsing config file: %v", err)
}
fs := flag.NewFlagSet("", flag.ContinueOnError)
mflag.VisitAll(func(f *mflag.Flag) {
for _, n := range f.Names {
if len(n) < 2 {
continue
}
n = strings.TrimPrefix(n, "-")
fs.Var(f.Value, n, f.Usage)
}
})
gconf.ParseSet("", fs)
}
示例7: ReadConfig
func ReadConfig(filename string) Config {
dbFlagSet := flag.NewFlagSet("mysql", flag.ExitOnError)
flagUser := dbFlagSet.String("username", "", "Database username")
flagPass := dbFlagSet.String("password", "", "Database password")
flagHost := dbFlagSet.String("host", "localhost", "Database host")
flagDbName := dbFlagSet.String("database", "", "Database name")
globalconf.Register("mysql", dbFlagSet)
conf, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: filename,
})
if err != nil {
log.Fatalf(err.Error())
}
conf.ParseAll()
return Config{
Username: *flagUser,
Host: *flagHost,
Password: *flagPass,
Database: *flagDbName,
}
}
示例8: GetConfig
func GetConfig() (*Config, error) {
c := &Config{}
var keyFile string
var keyContents string
var proxyProtoHttpsPorts string
flag.StringVar(&keyFile, "jwt-public-key-file", "", "Location of the public-key used to validate JWTs.")
flag.StringVar(&keyContents, "jwt-public-key-contents", "", "An alternative to jwt-public-key-file. The contents of the key.")
flag.StringVar(&c.ListenAddr, "listen-address", ":8080", "The tcp address to listen on.")
flag.StringVar(&c.CattleAddr, "cattle-address", "", "The tcp address to forward cattle API requests to. Will not proxy to cattle api if this option is not provied.")
flag.IntVar(&c.ParentPid, "parent-pid", 0, "If provided, this process will exit when the specified parent process stops running.")
flag.StringVar(&proxyProtoHttpsPorts, "https-proxy-protocol-ports", "", "If proxy protocol is used, a list of proxy ports that will allow us to recognize that the connection was over https.")
confOptions := &globalconf.Options{
EnvPrefix: "PROXY_",
}
conf, err := globalconf.NewWithOptions(confOptions)
if err != nil {
return nil, err
}
conf.ParseAll()
if keyFile != "" && keyContents != "" {
return nil, fmt.Errorf("Can't specify both jwt-public-key-file and jwt-public-key-contents")
}
var parsedKey interface{}
var parseErr error
if keyFile != "" {
parsedKey, parseErr = ParsePublicKey(keyFile)
} else if keyContents != "" {
parsedKey, parseErr = ParsePublicKeyFromMemory(keyContents)
} else {
parseErr = fmt.Errorf("Must specify one of jwt-public-key-file and jwt-public-key-contents")
}
if parseErr != nil {
return nil, parseErr
}
c.PublicKey = parsedKey
portMap := make(map[int]bool)
ports := strings.Split(proxyProtoHttpsPorts, ",")
for _, port := range ports {
if p, err := strconv.Atoi(port); err == nil {
portMap[p] = true
}
}
c.ProxyProtoHttpsPorts = portMap
return c, nil
}
示例9: Parse
func Parse() error {
flag.BoolVar(&Config.HaProxyMonitor, "haproxy-monitor", false, "Monitor HAProxy")
flag.IntVar(&Config.Port, "port", 8080, "Listen port")
flag.StringVar(&Config.Ip, "ip", "", "Listen IP, defaults to all IPs")
flag.StringVar(&Config.CAdvisorUrl, "cadvisor-url", "http://localhost:8081", "cAdvisor URL")
flag.StringVar(&Config.DockerUrl, "docker-host", "unix:///var/run/docker.sock", "Docker host URL")
flag.IntVar(&Config.NumStats, "num-stats", 600, "Number of stats to show by default")
flag.BoolVar(&Config.Auth, "auth", false, "Authenticate requests")
flag.StringVar(&Config.HostUuid, "host-uuid", "", "Host UUID")
flag.BoolVar(&Config.HostUuidCheck, "host-uuid-check", true, "Validate host UUID")
flag.StringVar(&Config.Key, "public-key", "", "Public Key for Authentication")
flag.IntVar(&Config.EventsPoolSize, "events-pool-size", 10, "Size of worker pool for processing docker events.")
flag.StringVar(&Config.CattleUrl, "cattle-url", "", "URL for accessing cattle api")
flag.StringVar(&Config.CattleAccessKey, "cattle-access-key", "", "Access key for cattle api")
flag.StringVar(&Config.CattleSecretKey, "cattle-secret-key", "", "Secret key for cattle api")
flag.StringVar(&Config.CattleStateDir, "cattle-state-dir", "", "Directory where Rancher state is persisted.")
flag.StringVar(&Config.PidFile, "pid-file", "", "PID file")
flag.StringVar(&Config.LogFile, "log", "", "Log file")
confOptions := &globalconf.Options{
EnvPrefix: "HOST_API_",
}
filename := os.Getenv("HOST_API_CONFIG_FILE")
if len(filename) > 0 {
confOptions.Filename = filename
}
conf, err := globalconf.NewWithOptions(confOptions)
if err != nil {
return err
}
conf.ParseAll()
if len(Config.Key) > 0 {
if err := ParsedPublicKey(); err != nil {
glog.Error("Error reading file")
return err
}
}
s, err := os.Stat("/run/systemd/system")
if err != nil || !s.IsDir() {
Config.Systemd = false
} else {
Config.Systemd = true
}
return nil
}
示例10: main
// TODO: html template
// TODO: email this out
// TODO: better comments
func main() {
// loading configuration
flag.Parse()
conf, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: config,
})
if err != nil {
log.Fatal(err)
}
conf.ParseAll()
ccAPI, _ := api.NewAPI(config, authToken, apiKey, daysBack, debug)
// Generate a report from a stored file
if prevReport != "" {
c := types.Load(prevReport)
c.BuildCampaignReport(getTopDomains, getTopClicks)
fmt.Println(types.Render(c))
os.Exit(0)
}
runTime := time.Now().Format("2006-01-02T15:04")
saveTo := fmt.Sprintf("./logs/%s.gob", runTime)
log.Print(runTime, saveTo)
camps, err := ccAPI.GetCampaigns()
if err != nil {
log.Fatal(err)
}
log.Print(camps)
log.Print("retrieved campaigns: ", len(camps.Campaigns))
for _, c := range camps.Campaigns {
err = ccAPI.GetCampaignDetail(c)
log.Print(err)
log.Print(c)
err = ccAPI.GetCampaignPreview(c)
log.Print(err)
err = ccAPI.GetCampaignTracking(c)
b, _ := json.MarshalIndent(c, "", " ")
fmt.Println(string(b))
}
types.Save(camps, saveTo)
camps.BuildCampaignReport(getTopDomains, getTopClicks)
fmt.Println(camps)
fmt.Println(types.Render(camps))
}
示例11: init
func init() {
chanmap = make(map[string]*hbot.IrcChannel)
config, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: configFile,
})
if err != nil {
log.Fatalf("Cannot parse configuration file: %s", err)
}
globalconf.Register("tumblr", tumblrConf)
globalconf.Register("twitter", twitterConf)
globalconf.Register("logger", loggerConf)
globalconf.Register("commands", commandsConf)
config.ParseAll()
}
示例12: ConfInit
func ConfInit() {
flag.Parse()
if *g_conf_file == "" {
//panic("please set conf file ")
println("have no config file")
return
}
conf, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: *g_conf_file,
})
if err != nil {
panic(err)
}
conf.ParseAll()
}
示例13: getConfig
func getConfig(flagset *flag.FlagSet, userCfgFile string) (*config.Config, error) {
opts := globalconf.Options{EnvPrefix: "API_HOSTD_"}
if userCfgFile != "" {
// Fail hard if a user-provided config is not usable
fi, err := os.Stat(userCfgFile)
if err != nil {
ctxLog.Fatalf("Unable to use config file %s: %v", userCfgFile, err)
}
if fi.IsDir() {
ctxLog.Fatalf("Provided config %s is a directory, not a file", userCfgFile)
}
opts.Filename = userCfgFile
} else if _, err := os.Stat(DefaultConfigFile); err == nil {
opts.Filename = DefaultConfigFile
}
gconf, err := globalconf.NewWithOptions(&opts)
if err != nil {
return nil, err
}
gconf.ParseSet("", flagset)
cfg := config.Config{
Verbosity: (*flagset.Lookup("verbosity")).Value.(flag.Getter).Get().(int),
IP: (*flagset.Lookup("ip")).Value.(flag.Getter).Get().(string),
Port: (*flagset.Lookup("port")).Value.(flag.Getter).Get().(string),
Secret: (*flagset.Lookup("jwt_sign_key")).Value.(flag.Getter).Get().(string),
CORSAllowedOrigins: config.StringToSlice((*flagset.Lookup("cors_allowed_origins")).Value.(flag.Getter).Get().(string)),
CORSAllowedMethods: config.StringToSlice((*flagset.Lookup("cors_allowed_methods")).Value.(flag.Getter).Get().(string)),
CORSAllowedHeaders: config.StringToSlice((*flagset.Lookup("cors_allowed_headers")).Value.(flag.Getter).Get().(string)),
CORSExposedHeaders: config.StringToSlice((*flagset.Lookup("cors_exposed_headers")).Value.(flag.Getter).Get().(string)),
CORSAllowCredentials: (*flagset.Lookup("cors_allow_credentials")).Value.(flag.Getter).Get().(bool),
CORSMaxAge: (*flagset.Lookup("cors_max_age")).Value.(flag.Getter).Get().(int),
CORSOptionsPassThrough: (*flagset.Lookup("cors_options_pass_through")).Value.(flag.Getter).Get().(bool),
CORSDebug: (*flagset.Lookup("cors_debug")).Value.(flag.Getter).Get().(bool),
}
log.SetLevel(log.Level(cfg.Verbosity))
ctxLog.Infof("Loaded config: [%+v]", cfg)
return &cfg, nil
}
示例14: ReadConfig
// Read config
//
// Initialize Config from Config File
func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager {
if !FileExist(ConfigFile) {
// create ConfigFile if it does not exist, otherwise
// globalconf will panic when trying to persist flags.
fmt.Printf("config file '%s' doesn't exist, creating it\n", ConfigFile)
os.Create(ConfigFile)
}
g, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: ConfigFile,
EnvPrefix: EnvPrefix,
})
if err != nil {
fmt.Println(err)
} else {
g.ParseAll()
}
cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true}
return cfg
}
示例15: GetConfig
func GetConfig() (*Config, error) {
c := &Config{}
var keyFile string
var keyContents string
flag.StringVar(&keyFile, "jwt-public-key-file", "", "Location of the public-key used to validate JWTs.")
flag.StringVar(&keyContents, "jwt-public-key-contents", "", "An alternative to jwt-public-key-file. The contents of the key.")
flag.StringVar(&c.ListenAddr, "listen-address", "localhost:8080", "The tcp address to listen on.")
flag.StringVar(&c.CattleAddr, "cattle-address", "", "The tcp address to forward cattle API requests to. Will not proxy to cattle api if this option is not provied.")
flag.IntVar(&c.ParentPid, "parent-pid", 0, "If provided, this process will exit when the specified parent process stops running.")
confOptions := &globalconf.Options{
EnvPrefix: "PROXY_",
}
conf, err := globalconf.NewWithOptions(confOptions)
if err != nil {
return nil, err
}
conf.ParseAll()
if keyFile != "" && keyContents != "" {
return nil, fmt.Errorf("Can't specify both jwt-public-key-file and jwt-public-key-contents")
}
var parsedKey interface{}
var parseErr error
if keyFile != "" {
parsedKey, parseErr = ParsePublicKey(keyFile)
} else if keyContents != "" {
parsedKey, parseErr = ParsePublicKeyFromMemory(keyContents)
} else {
parseErr = fmt.Errorf("Must specify one of jwt-public-key-file and jwt-public-key-contents")
}
if parseErr != nil {
return nil, parseErr
}
c.PublicKey = parsedKey
return c, nil
}