github.com/korsakjakub/snk@v0.0.0-20230625212658-1d6c119c67ee/config.go (about)

     1  package main
     2  
     3  import (
     4  	"github.com/spf13/viper"
     5  	"log"
     6  	"strconv"
     7  )
     8  
     9  type ConfigYaml struct {
    10  	Width  string `mapstructure:"width"`
    11  	Height string `mapstructure:"height"`
    12  }
    13  
    14  type Config struct {
    15  	Width  int
    16  	Height int
    17  }
    18  
    19  var vp *viper.Viper
    20  
    21  func loadConfig(args ...string) Config {
    22  	var confYaml ConfigYaml
    23  
    24  	vp = viper.New()
    25  	vp.SetConfigFile("config.yml")
    26  	vp.AddConfigPath(".")
    27  	for _, el := range args {
    28  		vp.AddConfigPath(el)
    29  	}
    30  	err := vp.ReadInConfig()
    31  	if err != nil {
    32  		log.Fatal("Cannot read the config file: ", err.Error())
    33  		return Config{}
    34  	}
    35  
    36  	err = vp.Unmarshal(&confYaml)
    37  	if err != nil {
    38  		log.Fatal("Cannot unmarshal the config file: ", err.Error())
    39  		return Config{}
    40  	}
    41  
    42  	w, err := strconv.Atoi(confYaml.Width)
    43  	h, err := strconv.Atoi(confYaml.Height)
    44  	return Config{Width: w, Height: h}
    45  }