[ 读取yaml配置[go] ]


读取yaml文件[go语言]

1.安装

go get -u "gopkg.in/yaml.v3"

2.文件setting.yaml

mysql:
  host: 47.120.55.99
  port: 3306
  db: go_test
  user: root
  password: chenhaifeng
  log_level: dev
  config: ""

system:
  host: "0.0.0.0"
  port: 8080
  env: debug

3.读取配置

type Config struct {
    Mysql  Mysql  `yaml:"mysql"`
    System System `yaml:"system"`
}

type Mysql struct {
    Host     string `yaml:"host"`
    Port     int    `yaml:"port"`
    DB       string `yaml:"db"`
    User     string `yaml:"user"`
    Password string `yaml:"password"`
    LogLevel string `yaml:"log_level"`
    Config   string `yaml:"config"`
}

type System struct {
    Host string `yaml:"host"`
    Port int    `yaml:"port"`
    Env  string `yaml:"env"`
}


func InitSetting() {
    dataBytes, err := os.ReadFile("settings.yaml")
    if err != nil {
        return
    }
    config := &Config{}
    // config := &config.Config{}
    err = yaml.Unmarshal(dataBytes, config)
    if err != nil {
        return
    }
    fmt.Printf("config → %+v\n", config) // config → {Mysql:{Url:127.0.0.1 Port:3306} Redis:{Host:127.0.0.1 Port:6379}}
}