You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.5 KiB
73 lines
1.5 KiB
package framework
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"k8s.io/apimachinery/pkg/api/errors"
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
var ConfigFileGroupResource = schema.GroupResource{
|
|
Group: "",
|
|
Resource: "config",
|
|
}
|
|
|
|
type Config struct {
|
|
*viper.Viper // 动态处理配置文件的工具
|
|
|
|
Stdout io.Writer
|
|
Stderr io.Writer
|
|
}
|
|
|
|
func NewConfig() *Config {
|
|
return &Config{
|
|
Viper: viper.New(),
|
|
Stdout: os.Stdout,
|
|
Stderr: os.Stderr,
|
|
}
|
|
}
|
|
|
|
// 从文件加载配置内容到 config 对象中
|
|
func (c *Config) Load(configFile string) error {
|
|
// 1. 设置文件名
|
|
c.SetConfigName(filepath.Base(configFile))
|
|
|
|
// 2. 甚至文件目录
|
|
c.AddConfigPath(filepath.Dir(configFile))
|
|
|
|
// 3. 读入文件
|
|
err := c.ReadInConfig()
|
|
|
|
// 4. 错误处理
|
|
if err != nil {
|
|
// 4.1 处理后缀
|
|
ext := filepath.Ext(configFile)
|
|
if _, ok := err.(viper.ConfigFileNotFoundError); ok && ext != "" {
|
|
c.SetConfigName(filepath.Base(configFile[:len(configFile)-len(ext)]))
|
|
err = c.ReadInConfig()
|
|
}
|
|
if err != nil {
|
|
switch err.(type) {
|
|
case viper.ConfigFileNotFoundError:
|
|
return errors.NewNotFound(ConfigFileGroupResource, fmt.Sprintf("config file \"%s\" not found", configFile))
|
|
case viper.UnsupportedConfigError:
|
|
return errors.NewBadRequest("using a not supperted file format")
|
|
default:
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *Config) WithWriter(std io.Writer) *Config {
|
|
c.Stdout = std
|
|
c.Stderr = std
|
|
return c
|
|
}
|