Created
October 7, 2021 18:37
-
-
Save romanwrites/5a8190df0bc615513b4c638bdd84a4e7 to your computer and use it in GitHub Desktop.
Read config.yml to struct in golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
login: "hello" | |
password: "world" | |
host: "localhost" | |
port: "8080" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module auth-tests | |
go 1.15 | |
require github.com/spf13/viper v1.9.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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