config: add a Require message.

Also update explanation of the intended use-case for this package.
This commit is contained in:
Kyle Isom 2020-03-02 17:36:29 -08:00
parent ef0f14a512
commit 2b6ae03d1a
1 changed files with 26 additions and 0 deletions

View File

@ -1,6 +1,11 @@
// Package config implements a simple global configuration system that
// supports a file with key=value pairs and environment variables. Note
// that the config system is global.
//
// This package is intended to be used for small daemons: some configuration
// file is optionally populated at program start, then this is used to
// transparently look up configuration values from either that file or the
// environment.
package config
import (
@ -82,3 +87,24 @@ func GetDefault(key, def string) string {
}
return def
}
// Require retrieves a value from either a configuration file or the
// environment. If the key isn't present, it will call log.Fatal, printing
// the missing key.
func Require(key string) string {
if v, ok := vars[key]; ok {
return v
}
v, ok := os.LookupEnv(prefix + key)
if !ok {
var envMessage string
if prefix != "" {
envMessage = " (note: looked for the key " + prefix + key
envMessage += " in the local env)"
}
log.Fatalf("missing required configuration value %s%s", key, envMessage)
}
return v
}