golang yaml配置

  • Redis配置文件结构体
package config

type Redis struct {
	Host     string `yaml:"host"`
	Password string `yaml:"password"`
	Port     int    `yaml:"port"`
	DB       int    `yaml:"db"`
}

  • 日志配置文件结构体
package config

type Logger struct {
	LogPath string `yaml:"logPath"`
	Debug   bool   `yaml:"debug"`
}

  • 将配置文件的各个结构体汇总
package config

type Config struct {
	Redis      Redis      `yaml:"redis"`
	Logger     Logger     `yaml:"logger"`
}

  • 定义一个全局的结构体变量,在整个项目中使用
package global

import "test/config"

var (
	Cfg config.Config
)

  • 读取配置yaml配置文件,将内容映射到全局变量中
package initialization

import (
	"test/global"
	"gopkg.in/yaml.v2"
	"log"
	"os"
)

func initConfig() {
	configFile, err := os.ReadFile("config.yaml")
	if err != nil {
		log.Fatal("读取配置文件错误!", err)
	}

	if err = yaml.Unmarshal(configFile, &global.Cfg); err != nil {
		log.Fatal("加载配置文件错误!", err)
	}
}

  • 配置文件写法
redis:
  host: "127.0.0.1"
  port: 6379
  password: ""
  db: 0
logger:
  logPath: "./log/test.log"
  debug: true

posted on 2023-02-25 16:22  信奉上帝的小和尚  阅读(314)  评论(0编辑  收藏  举报

导航