go配置文件读取

一个强大简单好用的配置解决方案,Viper

Viper具有以下特性:

  • 设置默认值
  • 可以读取如下格式的配置文件:JSON、TOML、YAML、HCL
  • 监控配置文件改动,并热加载配置文件
  • 从环境变量读取配置
  • 从远程配置中心读取配置(etcd/consul),并监控变动
  • 从命令行 flag 读取配置
  • 从缓存中读取配置
  • 支持直接设置配置项的值

Viper的读取顺序:

  • viper.Set() 所设置的值
  • 命令行 flag
  • 环境变量
  • 配置文件
  • 配置中心:etcd/consul
  • 默认值

Viper在初始化之后,只需要调用viper.GetString()viper.GetInt()viper.GetBool() 等函数即可得到配置文件中对应的参数。

Viper 也可以非常方便地读取多个层级的配置,比如这样一个 YAML 格式的配置:

common:
    db:
        name: db
        addr: 127.0.0.1:3306
        username: root
        password: root

如果要读取name,只需要执行viper.GetString("common.db.name")就可以

下面来一个简单的例子介绍Viper:
config/config.go

package config

import (
    "strings"
    "github.com/fsnotify/fsnotify"
    "github.com/spf13/viper"
)

type Config struct {
    Name string
}

func Init(cfg string) error {
    c := Config{
        Name: cfg,
    }
    // 初始化配置文件
    if err := c.initConfig(); err != nil {
        return err
    }
    
    c.watchConfig()

    return nil
}

func (c *Config) initConfig() error {
    if c.Name != "" {
       // 如果指定了配置文件,则解析指定的配置文件
        viper.SetConfigFile(c.Name)
    } else {
       // 如果没有指定配置文件,则解析默认的配置文件
        viper.AddConfigPath("conf")
        viper.SetConfigName("config")
    }
   // 设置配置文件格式为YAML
    viper.SetConfigType("yaml")
    // viper解析配置文件
    if err := viper.ReadInConfig(); err != nil {
        return err
    }

    return nil
}

// 监听配置文件是否改变,用于热更新
func (c *Config) watchConfig() {
    viper.WatchConfig()
    viper.OnConfigChange(func(e fsnotify.Event) {
        fmt.Printf("Config file changed: %s\n", e.Name)
    })
}

conf/config.yaml

name: demo
common:
    db:
        name: db
        addr: 127.0.0.1:3306
        username: root
        password: root

main.go

package main

import (
    "test/config"
  "fmt"
    "github.com/spf13/viper"
)

func main() {

    if err := config.Init(""); err != nil {
        panic(err)
    }

    name := viper.GetString("name")

    fmt.Println("Viper get name:",name)
}

执行go run main.go

Viper get name: demo

go配置文件读取_第1张图片
image

微信搜索「goentry-xyz」,关注公众号「灯下独码」

你可能感兴趣的:(go配置文件读取)