lyricdownloader/config.go

55 lines
1.1 KiB
Go
Raw Permalink Normal View History

package main
import (
"encoding/json"
"fmt"
"os"
"path"
)
// isFile - check if fp is a valid file
func isFile(fp string) bool {
info, err := os.Stat(fp)
if os.IsNotExist(err) || !info.Mode().IsRegular() {
return false
}
return true
}
// getConfig - parse config json file
func getConfig(filepath string) (Config, error) {
// if filepath is not empty
// try to load the token from the file
// else load it from user homedir
var config Config
configFilePath := filepath
ok := isFile(filepath)
if !ok {
if printDebug {
mainLog.Println("Loading config from home directory...")
}
dirname, err := os.UserConfigDir()
if err != nil {
return config, err
}
configFilePath := path.Join(dirname, "lyricdownloader/config.json")
ok := isFile(configFilePath)
if !ok {
return config, fmt.Errorf("%s/lyricdownloader/config.json file is not found", dirname)
}
}
configFile, err := os.Open(configFilePath)
if err != nil {
return config, err
}
defer configFile.Close()
err = json.NewDecoder(configFile).Decode(&config)
if err != nil {
return config, err
}
return config, nil
}