Created
March 12, 2020 09:08
-
-
Save andy221166/a5bfc26bb4c4fca5bb9053df18c74d25 to your computer and use it in GitHub Desktop.
Golang read YAML file
This file contains 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 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