Skip to content

Instantly share code, notes, and snippets.

@stndrf
Last active September 3, 2021 07:49
Show Gist options
  • Save stndrf/a0d2c555dd54098b88ca7307baee24f2 to your computer and use it in GitHub Desktop.
Save stndrf/a0d2c555dd54098b88ca7307baee24f2 to your computer and use it in GitHub Desktop.
Golang: read yaml (v3) config
package config
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v3"
)
type Config struct {
Client struct {
IP string
Port int
User string
Password string
}
Server struct {
IP string
Port int
}
}
func ReadConfig(filename string) (*Config, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
cfg := &Config{}
err = yaml.Unmarshal(buf, cfg)
if err != nil {
return nil, fmt.Errorf("in file %q: %v", filename, err)
}
return cfg, nil
}
Client:
IP: 1.2.3.4
Port: 8080
User: Paul
Password: secret
Server:
IP: 0.0.0.0
Port: 8080

Usage

cfg, err := config.ReadConfig("./config.yml")
if err != nil {
	fmt.Fatal(err)
}

fmt.Printf("%s", cfg.Client.IP)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment