Add a function to parse viper

None of these `filename`, `ext` or `configPath` should be in `main`,
they are all just for creating a instance of Viper and then nothing.
Do it in a separate function will make the function `main` more readable.

Signed-off-by: Hu Keping <hukeping@huawei.com>
This commit is contained in:
HuKeping 2015-12-07 14:27:09 +08:00
parent a3d2974e1b
commit bfe7316de9
3 changed files with 44 additions and 12 deletions

View File

@ -12,7 +12,6 @@ import (
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
@ -181,17 +180,9 @@ func main() {
// when the signer starts print the version for debugging and issue logs later
logrus.Infof("Version: %s, Git commit: %s", version.NotaryVersion, version.GitCommit)
filename := filepath.Base(configFile)
ext := filepath.Ext(configFile)
configPath := filepath.Dir(configFile)
mainViper.SetConfigType(strings.TrimPrefix(ext, "."))
mainViper.SetConfigName(strings.TrimSuffix(filename, ext))
mainViper.AddConfigPath(configPath)
if err := mainViper.ReadInConfig(); err != nil {
logrus.Errorf("Could not read config at :%s, viper error: %v", configFile, err)
os.Exit(1)
// parse viper config
if err := utils.ParseViper(mainViper, configFile); err != nil {
logrus.Fatal(err.Error())
}
// default is error level

View File

@ -159,3 +159,19 @@ func SetUpBugsnag(config *bugsnag.Configuration) error {
}
return nil
}
// ParseViper tries to parse out a Viper from a configuration file.
func ParseViper(v *viper.Viper, configFile string) error {
filename := filepath.Base(configFile)
ext := filepath.Ext(configFile)
configPath := filepath.Dir(configFile)
v.SetConfigType(strings.TrimPrefix(ext, "."))
v.SetConfigName(strings.TrimSuffix(filename, ext))
v.AddConfigPath(configPath)
if err := v.ReadInConfig(); err != nil {
return fmt.Errorf("Could not read config at :%s, viper error: %v", configFile, err)
}
return nil
}

View File

@ -335,3 +335,28 @@ func TestParseTLSWithEnvironmentVariables(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, expected, *tlsOpts)
}
func TestParseViperWithInvalidFile(t *testing.T) {
v := viper.New()
SetupViper(v, envPrefix)
err := ParseViper(v, "Chronicle_Of_Dark_Secrets.json")
assert.Error(t, err)
assert.Contains(t, err.Error(), "Could not read config")
}
func TestParseViperWithValidFile(t *testing.T) {
file, err := os.Create("/tmp/Chronicle_Of_Dark_Secrets.json")
assert.NoError(t, err)
defer os.Remove(file.Name())
file.WriteString(`{"logging": {"level": "debug"}}`)
v := viper.New()
SetupViper(v, envPrefix)
err = ParseViper(v, "/tmp/Chronicle_Of_Dark_Secrets.json")
assert.NoError(t, err)
assert.Equal(t, "debug", v.GetString("logging.level"))
}