Skip to content
鼓励作者:欢迎打赏犒劳

go配置文件

本工具类用的是github.com/spf13/viper框架实现。很方便的将yml文件映射成struct,还有监听的功能

配置类

go
package config

import "time"

type Config struct {
	App           App           `mapstructure:"app" yaml:"app"`
	Database      Database      `mapstructure:"database" yaml:"database"`
	MongoDB       MongoDB       `mapstructure:"mongodb"`
	Redis         Redis         `mapstructure:"redis" yaml:"redis"`
	Elasticsearch Elasticsearch `mapstructure:"elasticsearch" yaml:"elasticsearch"`
}

type App struct {
	RunMode         string `mapstructure:"run_mode"  yaml:"run_mode"`
	RuntimeRootPath string `mapstructure:"runtime_root_path" yaml:"runtime_root_path"`
	LogSavePath     string `mapstructure:"log_save_path" yaml:"log_save_path"`
	LogSaveName     string `mapstructure:"log_save_name" yaml:"log_save_name"`
	LogFileExt      string `mapstructure:"log_file_ext" yaml:"log_file_ext"`
	TimeFormat      string `mapstructure:"time_format" yaml:"time_format"`
	Task            string `mapstructure:"task" yaml:"task"`
}

type Database struct {
	Type        string `mapstructure:"type" yaml:"type"`
	User        string `mapstructure:"user" yaml:"user"`
	Password    string `mapstructure:"password" yaml:"password"`
	Host        string `mapstructure:"host" yaml:"host"`
	Name        string `mapstructure:"name" yaml:"name"`
	TablePrefix string `mapstructure:"table-prefix" yaml:"table-prefix"`
}

type Redis struct {
	Host        string        `mapstructure:"host" yaml:"host"`
	Password    string        `mapstructure:"password" yaml:"password"`
	IdleTimeout time.Duration `mapstructure:"idle-timeout" yaml:"idle-timeout"`
}

type Elasticsearch struct {
	Hosts    []string `mapstructure:"hosts" yaml:"hosts"`
	Username string   `mapstructure:"username" yaml:"username"`
	Password string   `mapstructure:"password" yaml:"password"`
}

type MongoDB struct {
	DBname   string   `mapstructure:"dbname"`
	User     string   `mapstructure:"user"`
	Password string   `mapstructure:"password"`
	Host     []string `mapstructure:"host"`
}

配置文件

text
app:
  domain: localhost
  run_mode: dev
  time_format: 20060102
  runtime_root_path: 'runtime/'
  log_save_path: 'logs/'
  log_save_name: 'log'
  log_file_ext: 'log'
  task: 'order-rebuild'

database:
  type: 'mysql'
  user: 'root'
  password: 'admin123'
  host: '127.0.0.1:3306'
  name: 'shop'
  table_prefix:

mongodb:
  dbname: shop
  user: admin
  password: admin123
  host: ["127.0.0.1:27017"]

redis:
  host: '127.0.0.1:6379'
  password:
  idle_timeout: 200

elasticsearch:
  hosts: ["https://127.0.0.1:9200"]
  username: "elastic"
  password: "elastic"

测试类

go
package main

import (
	"demo/config"
	"fmt"
	"time"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var (
	CONFIG config.Config
)

// 加载配置,失败直接panic
func LoadConfig() {
	viper := viper.New()
	//1.设置配置文件路径
	viper.SetConfigFile("config/config.yml")
	//2.配置读取
	if err := viper.ReadInConfig(); err != nil {
		panic(err)
	}
	//3.将配置映射成结构体
	if err := viper.Unmarshal(&CONFIG); err != nil {
		panic(err)
	}

	//4. 监听配置文件变动,重新解析配置
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Printf("%v 修改了\n", e.Name)
		if err := viper.Unmarshal(&CONFIG); err != nil {
			panic(err)
		}
	})
}
func main() {
	LoadConfig()
	//创建定时器,每隔1秒后,定时器就会给channel发送一个事件(当前时间)
	ticker := time.NewTicker(time.Second * 3)
	for { //循环
		x := <-ticker.C
		fmt.Printf(" x = %v \n", x)
		fmt.Println(CONFIG)
	}

}

如有转载或 CV 的请标注本站原文地址