- 安装
go get gopkg.in/yaml.v3
- 创建yaml
Mysql:
Host: 192.168.214.134
Port: 3306
UserName: ww
Password: ww
Database: go_db
Charset: utf8mb4
ParseTime: true
Loc: Local
ListValue:
- haha
- test
- vv
JWTSecret: nidaye
- 定义结构体
type Mysql struct {
Host string `yaml:"Host"`
Port int `yaml:"Port"`
UserName string `yaml:"UserName"`
Password string `yaml:"Password"`
Database string `yaml:"Database"`
Charset string `yaml:"Charset"`
ParseTime bool `yaml:"ParseTime"`
Loc string `yaml:"Loc"`
ListValue []string `yaml:"ListValue"`
}
type YamlStruct struct {
Mysql Mysql `yaml:"Mysql"`
JWTSecret string `yaml:"JWTSecret"`
}
- 读取
package main
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
)
type Mysql struct {
Host string `yaml:"Host"`
Port int `yaml:"Port"`
UserName string `yaml:"UserName"`
Password string `yaml:"Password"`
Database string `yaml:"Database"`
Charset string `yaml:"Charset"`
ParseTime bool `yaml:"ParseTime"`
Loc string `yaml:"Loc"`
ListValue []string `yaml:"ListValue"`
}
type YamlStruct struct {
Mysql Mysql `yaml:"Mysql"`
JWTSecret string `yaml:"JWTSecret"`
}
func ReadConf(filename string) (*YamlStruct, error) {
buf, err := os.ReadFile(filename)
c := YamlStruct{}
if err != nil {
return nil, err
} else {
err2 := yaml.Unmarshal(buf, &c)
if err2 != nil {
return nil, err2
} else {
return &c, nil
}
}
}
func main() {
c, _ := ReadConf("./config.yaml")
fmt.Printf("c: %v\n", c.Mysql.ListValue)
}