package file import ( "bytes" "errors" "fmt" "io/ioutil" "github.com/spf13/viper" "gopkg.in/yaml.v2" ) func WriteToFile(fileName string, cfg interface{}) error { b, err := yaml.Marshal(cfg) if err != nil { return err } b = addRootIndent(b, 1) if err := ioutil.WriteFile(fmt.Sprintf("%s.yml", fileName), b, 0644); err != nil { return err } return nil } func addRootIndent(b []byte, n int) []byte { prefix := append([]byte("\n"), bytes.Repeat([]byte(" "), n)...) b = append(prefix[1:], b...) return bytes.ReplaceAll(b, []byte("\n"), prefix) } // Загрузка конфигурации func Load(fileName string) (*viper.Viper, error) { v := viper.New() v.SetConfigName(fmt.Sprintf("./%s", fileName)) v.AddConfigPath(".") v.AutomaticEnv() if err := v.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { return nil, errors.New("config file not found") } return nil, err } return v, nil }