cfg, err := config.ReadConfig("./config.yml")
if err != nil {
fmt.Fatal(err)
}
fmt.Printf("%s", cfg.Client.IP)
Last active
September 3, 2021 07:49
-
-
Save stndrf/a0d2c555dd54098b88ca7307baee24f2 to your computer and use it in GitHub Desktop.
Golang: read yaml (v3) config
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 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 | |
} |
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
Client: | |
IP: 1.2.3.4 | |
Port: 8080 | |
User: Paul | |
Password: secret | |
Server: | |
IP: 0.0.0.0 | |
Port: 8080 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment