96 lines
1.7 KiB
Go
96 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
const (
|
|
DefaultAPIURL = "https://api.blackroad.io/v1"
|
|
)
|
|
|
|
type Config struct {
|
|
APIKey string `mapstructure:"api_key"`
|
|
APIURL string `mapstructure:"api_url"`
|
|
Output string `mapstructure:"output"`
|
|
Timeout int `mapstructure:"timeout"`
|
|
}
|
|
|
|
var cfg *Config
|
|
|
|
func Init() error {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
configDir := filepath.Join(home, ".blackroad")
|
|
if err := os.MkdirAll(configDir, 0755); err != nil {
|
|
return err
|
|
}
|
|
|
|
viper.SetConfigName("config")
|
|
viper.SetConfigType("yaml")
|
|
viper.AddConfigPath(configDir)
|
|
viper.AddConfigPath(".")
|
|
|
|
// Set defaults
|
|
viper.SetDefault("api_url", DefaultAPIURL)
|
|
viper.SetDefault("output", "table")
|
|
viper.SetDefault("timeout", 30)
|
|
|
|
// Environment variables
|
|
viper.SetEnvPrefix("BLACKROAD")
|
|
viper.AutomaticEnv()
|
|
|
|
// Read config file if exists
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
|
|
return err
|
|
}
|
|
}
|
|
|
|
cfg = &Config{}
|
|
if err := viper.Unmarshal(cfg); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Override with env vars
|
|
if key := os.Getenv("BLACKROAD_API_KEY"); key != "" {
|
|
cfg.APIKey = key
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func Get() *Config {
|
|
if cfg == nil {
|
|
cfg = &Config{
|
|
APIURL: DefaultAPIURL,
|
|
Output: "table",
|
|
Timeout: 30,
|
|
}
|
|
}
|
|
return cfg
|
|
}
|
|
|
|
func Save() error {
|
|
home, _ := os.UserHomeDir()
|
|
configPath := filepath.Join(home, ".blackroad", "config.yaml")
|
|
return viper.WriteConfigAs(configPath)
|
|
}
|
|
|
|
func Set(key, value string) {
|
|
viper.Set(key, value)
|
|
switch key {
|
|
case "api_key":
|
|
cfg.APIKey = value
|
|
case "api_url":
|
|
cfg.APIURL = value
|
|
case "output":
|
|
cfg.Output = value
|
|
}
|
|
}
|