Initial Commit
This commit is contained in:
46
providers/file/file.go
Normal file
46
providers/file/file.go
Normal file
@ -0,0 +1,46 @@
|
||||
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
|
||||
}
|
21
providers/file/file_test.go
Normal file
21
providers/file/file_test.go
Normal file
@ -0,0 +1,21 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
// f "gitlab.tp.digitech.ru/ecom/configurator/pkg/providers/file"
|
||||
)
|
||||
|
||||
type TestWrite struct {
|
||||
test string
|
||||
}
|
||||
|
||||
func TestWriteToFile(t *testing.T) {
|
||||
|
||||
if err := WriteToFile("../../../testWrite", TestWrite{test: "WriteToFileTest"}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := os.Remove("../../../testWrite.yml"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user