yaml 文件是目前最常用的配置文件,使用go语言编写代码和工具时,也会用到yaml文件,将服务配置及中间件等信息定义到yaml文件中,那么如何将yaml文件中定义的信息读取到代码中进行使用呢?此处使用yaml包和viper包来解析配置文件,后续可根据实际场景来选用。
一、yaml包
yaml包这里使用”gopkg.in/yaml.v2”,以下为示例代码:
1、定义yaml配置文件
#config.yaml
listen: ':8050'
secret_key: 123
bowls: false
strslice:
  - 'asd'
  - 'qwe'
auth:
  - id: 'root'
    password: '456'
    roles:
      - 'admin'
  - id: 'cjs'
    password: '123'
    roles:
      - 'one'
keymap:
  a: 'xml'
  b: 'opi'
  c: 'edg'2、主程序
package main
import (
    "fmt"
    "io/ioutil"
    "os"
    v2 "gopkg.in/yaml.v2"
)
var (
    cfgFile = "config.yaml"
)
type user struct {                 #定义user结构体
    Id       string   `yaml:"id"`
    Password string   `yaml:"password"`
    Roles    []string `yaml:"roles"`
}
type Config struct {        #定义Config结构体
    Listen    string            `yaml:"listen"`
    SecretKey int               `yaml:"secret_key"`
    Boll      bool              `yaml:"bowls"`
    StrSlice  []string          `yaml:"strslice"`
    Auth      []user            `yaml:"auth"`
    KeyMap    map[string]string `yaml:"keymap"`
}
func test() {
    data, err := ioutil.ReadFile(cfgFile)
    if err != nil {
        fmt.Printf("err: %v\n", err)
        return
    }
    conf := new(Config)
    if err := v2.Unmarshal(data, conf); err != nil {        #使用yaml.Unmarshal将yaml文件中的信息反序列化给Config结构体
        fmt.Printf("err: %v\n", err)
        return
    }
    fmt.Printf("conf: %v\n", conf)                     
    fmt.Printf("conf.SecretKey: %v\n", conf.SecretKey)  #通过结构体语法取值
    out, err := v2.Marshal(conf)                    #序列化为yaml格式文件
    if err != nil {
        fmt.Printf("err: %v\n", err)
        return
    }
    fmt.Printf("out: %v\n", string(out))
    return
}
func main() {
    test()
}3、输出结果
conf: &{:8050 123 false [asd qwe] [{root 456 [admin]} {cjs 123 [one]}] map[a:xml b:opi c:edg]}
conf.SecretKey: 123
out: listen: :8050
secret_key: 123
bowls: false
strslice:
- asd
- qwe
auth:
- id: root
  password: "456"
  roles:
  - admin
- id: cjs
  password: "123"
  roles:
  - one
keymap:
  a: xml
  b: opi
  c: edg作者:wushaoyu
链接: https://www.cnblogs.com/wushaoyu/p/16644430.html
 我的书签
 我的书签
                                 添加书签
 添加书签 移除书签
 移除书签