一、介绍
yaml作为配置文件,根本在go中,被认为默认的配置文件格式了。
yaml格局介绍,详见 https://www.ruanyifeng.com/bl…
咱们看上面的yaml文件,新建redis.yaml文件
---
users:
- name: "hi"
age: 1
- name: "fff"
age: 2
redis:
base:
addr: "test.redis.com:6379"
password: "pwd"
db: "1"
二、go读取yaml文件
咱们应用 https://github.com/go-yaml/yaml 作为读取yaml的库。
import (
"gopkg.in/yaml.v3"
"io/ioutil"
"testing"
)
func TestYaml(t *testing.T) {
//1读取文件
data, err := ioutil.ReadFile("redis.yaml")
if err != nil {
t.Log(err)
}
t.Log(string(data))
//2解析文件
var y YamlFile
err = yaml.Unmarshal(data, &y)
t.Log(y, err)
}
type YamlFile struct {
Users []struct {
Name string
Age int
}
Redis struct {
Base struct {
Addr string
Password string
Db string
}
}
}
发表回复