Skip to content

Instantly share code, notes, and snippets.

@andy221166
Created March 12, 2020 09:08
Show Gist options
  • Save andy221166/a5bfc26bb4c4fca5bb9053df18c74d25 to your computer and use it in GitHub Desktop.
Save andy221166/a5bfc26bb4c4fca5bb9053df18c74d25 to your computer and use it in GitHub Desktop.
Golang read YAML file
package config
import "os"
import "log"
import "gopkg.in/yaml.v3"
const CONFIG_PATH = "/path/to/config.yml"
type Config struct {
Conn struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password"`
AuthenticationDatabase string `yaml:"authenticationDatabase"`
} `yaml:"conn"`
Tmp string `yaml:"tmp"`
}
func ReadConfig() Config {
var config Config
// Open YAML file
file, err := os.Open(CONFIG_PATH)
if err != nil {
log.Println(err.Error())
}
defer file.Close()
// Decode YAML file to struct
if file != nil {
decoder := yaml.NewDecoder(file)
if err := decoder.Decode(&config); err != nil {
log.Println(err.Error())
}
}
return config
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment