读取*.yaml配置文件

假设有如下内容的demo.yaml配置文件
 
########## MySQL连接参数 ##########
database:
  host: "localhost"             # 服务器主机地址
  name: "dbname"                # 数据库名
  port: 3306                    # 服务端口号
  user: "user_root"             # 账号
  pass: "pass_1234"             # 密码
  lang: "PHP;Go;Java"           # 测试
  form: "input#textarea#select" # 测试

########## Redis连接参数 ##########
redis:
  host: "localhost"  # 服务器主机地址
  port: 6379         # 服务端口号
  auth: "auth_redis" # 认证密码

#========== 总结 ==========#
# 1、冒号右边的值可以选择是否用双引号包围,建议字符串类型用双引号包围,数字类型不用双引号包围。
 
 
 
读取demo.yaml配置文件

package main

import (
   "fmt"
   "gopkg.in/yaml.v3"
   "os"
   "path/filepath"
)

func main() {
   // 读取yaml配置文件内容
   path, _ := filepath.Abs(".")
   contents, _ := os.ReadFile(path + "/demo.yaml")

   // 把读取的yaml配置文件内容放入map
   var conf map[string]map[string]string
   _ = yaml.Unmarshal(contents, &conf)

   // 展示database节点的配置
   database := conf["database"]
   fmt.Printf("database.host = %+v \n", database["host"]) // database.host = localhost
   fmt.Printf("database.name = %+v \n", database["name"]) // database.name = dbname
   fmt.Printf("database.port = %+v \n", database["port"]) // database.port = 3306
   fmt.Printf("database.user = %+v \n", database["user"]) // database.user = user_root
   fmt.Printf("database.pass = %+v \n", database["pass"]) // database.pass = pass_1234
   fmt.Printf("database.lang = %+v \n", database["lang"]) // database.lang = PHP;Go;Java
   fmt.Printf("database.form = %+v \n", database["form"]) // database.form = input#textarea#select

   // 展示redis节点的配置
   redis := conf["redis"]
   fmt.Printf("redis.host = %+v \n", redis["host"]) // redis.host = localhost
   fmt.Printf("redis.port = %+v \n", redis["port"]) // redis.port = 6379
   fmt.Printf("redis.auth = %+v \n", redis["auth"]) // redis.auth = auth_redis
}

Copyright © 2024 码农人生. All Rights Reserved