Skip to content

Instantly share code, notes, and snippets.

@romanwrites
Created October 7, 2021 18:37
Show Gist options
  • Save romanwrites/5a8190df0bc615513b4c638bdd84a4e7 to your computer and use it in GitHub Desktop.
Save romanwrites/5a8190df0bc615513b4c638bdd84a4e7 to your computer and use it in GitHub Desktop.
Read config.yml to struct in golang
login: "hello"
password: "world"
host: "localhost"
port: "8080"
module auth-tests
go 1.15
require github.com/spf13/viper v1.9.0
package main
import (
"fmt"
"github.com/spf13/viper"
"log"
"strconv"
)
type Configuration struct {
Login string `yml:"login"`
Password string `yml:"password"`
Host string `yml:"host"`
Port int `yml:"port"`
}
const (
filename = "config"
configDir = "."
)
var (
config *Configuration
)
func readConfiguration() *Configuration {
log.Println("read `" + filename + "`")
viper.SetConfigName(filename)
viper.AddConfigPath(configDir)
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %w \n", err))
}
config := &Configuration{}
err = viper.Unmarshal(config)
if err != nil {
log.Printf("unable to decode into config struct, %v\n", err)
}
return config
}
func init() {
config = readConfiguration()
}
func main() {
log.Println("login: " + config.Login)
log.Println("password: " + config.Password)
log.Println("host: " + config.Host)
log.Println("port: " + strconv.Itoa(config.Port))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment