How to read a YAML file in GO.
web:
port: 8000
db:
driver: mysql
host: localhost
user: test
pass: letmein
name: testDB
port: 3306
package main
import (
"io/ioutil"
"log"
"gopkg.in/yaml.v2"
)
type Settings struct {
Web struct {
Port int
}
DB struct {
Driver string
Host string
User string
Pass string
Name string
Port int
}
}
func LoadSettings(f string) *Settings {
dat, err := ioutil.ReadFile(f)
if err != nil {
log.Fatalln(err)
}
s := Settings{}
err = yaml.Unmarshal([]byte(dat), &s) // err has already been defined
if err != nil {
log.Fatalln(err)
}
return &s
}
func main() {
//arrange
host := "localhost"
port := 3306
dbuser := "test"
dbpass := "letmein"
dbname := "testDB"
webport := 8000
//act
s := LoadSettings("configtest.yml")
//assert
if host != s.DB.Host {
log.Fatal("host does not match")
}
if port != s.DB.Port {
log.Fatal("port does not match")
}
if dbuser != s.DB.User {
log.Fatal("user does not match")
}
if dbpass != s.DB.Pass {
log.Fatal("pass does not match")
}
if dbname != s.DB.Name {
log.Fatal("name does not match")
}
if webport != s.Web.Port {
log.Fatal("port does not match")
}
}