首页 > 编程语言 > 详细

Go语言读取各种配置文件

时间:2020-05-10 15:44:13      阅读:294      评论:0      收藏:0      [点我收藏+]

一、读取json

config.json

{
  "log": {
    "prefix": "[MY-LOG] ",
    "logFile": true,
    "stdout": "DEBUG",
    "file": "WARNING"
  }
}

config.go

type Log struct {
	Prefix  string `mapstructure:"prefix" json:"prefix"`
	LogFile bool   `mapstructure:"log-file" json:"logFile"`
	Stdout  string `mapstructure:"stdout" json:"stdout"`
	File    string `mapstructure:"file" json:"file"`
}

type Config struct {
	Log Log `json:"log"`
}

var (
	CONFIG config.Config
	LOG    *oplogging.Logger
) 

读取配置

func InitConfigFromJson() {
	// 打开文件
	RootPath, _ = os.Getwd()
	config_path := path.Join(RootPath, "config", "config.json")
	file, _ := os.Open(config_path)
	// 关闭文件
	defer file.Close()
	//NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据。
	decoder := json.NewDecoder(file)
	//Decode从输入流读取下一个json编码值并保存在v指向的值里
	err := decoder.Decode(&global.CONFIG)
	if err != nil {
		panic(err)
	}
}

二、读取key-value

config.txt

ip=127.0.0.1
port=3344

读取

package main

import (
	"bufio"
	"io"
	"os"
	"strings"
)

//读取key=value类型的配置文件
func InitConfig(path string) map[string]string {
	config := make(map[string]string)

	f, err := os.Open(path)
	defer f.Close()
	if err != nil {
		panic(err)
	}

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}
		s := strings.TrimSpace(string(b))
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}
		key := strings.TrimSpace(s[:index])
		if len(key) == 0 {
			continue
		}
		value := strings.TrimSpace(s[index+1:])
		if len(value) == 0 {
			continue
		}
		config[key] = value
	}
	return config
}

func main() {
	config := InitConfig("config.txt")
	ip := config["ip"]
	port := config["port"]

	fmt.Println("ip=",string(ip)," port=",string(port))
}

三、万能的viper

Viper是一个方便Go语言应用程序处理配置信息的库。它可以处理多种格式的配置。它支持的特性:

  • 设置默认值
  • 从JSON、TOML、YAML、HCL和Java properties文件中读取配置数据
  • 可以监视配置文件的变动、重新读取配置文件
  • 从环境变量中读取配置数据
  • 从远端配置系统中读取数据,并监视它们(比如etcd、Consul)
  • 从命令参数中读物配置
  • 从buffer中读取
  • 调用函数设置配置信息

config.json

#json文件
{
  "appId": "123456789",
  "secret": "maple123456",
  "host": {
    "address": "localhost",
    "port": 5799
  }
}

读取

package main

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

//定义config结构体
type Config struct {
    AppId string
    Secret string
    Host Host
}
//json中的嵌套对应结构体的嵌套
type Host struct {
    Address string
    Port int
}

func main() {
    config := viper.New()
    config.AddConfigPath("./kafka_demo")
    config.SetConfigName("config")
    config.SetConfigType("json")
    if err := config.ReadInConfig(); err != nil {
        panic(err)
    }
    v.WatchConfig()
    v.OnConfigChange(func(e fsnotify.Event) {
	 fmt.Println("config file changed:", e.Name)
         if err := config.ReadInConfig(); err != nil {
              panic(err)
           }
	})
    fmt.Println(config.GetString("appId"))
    fmt.Println(config.GetString("secret"))
    fmt.Println(config.GetString("host.address"))
    fmt.Println(config.GetString("host.port"))

    //直接反序列化为Struct
    var configjson Config
    if err :=config.Unmarshal(&configjson);err !=nil{
        fmt.Println(err)
    }

    fmt.Println(configjson.Host)
    fmt.Println(configjson.AppId)
    fmt.Println(configjson.Secret)

config.yaml

log:
  prefix: ‘[MY-LOG] ‘
  log-file: true
  stdout: ‘DEBUG‘
  file: ‘DEBUG‘

config.go

type Log struct {
	Prefix  string `mapstructure:"prefix" json:"prefix"`
	LogFile bool   `mapstructure:"log-file" json:"logFile"`
	Stdout  string `mapstructure:"stdout" json:"stdout"`
	File    string `mapstructure:"file" json:"file"`
}

type Config struct {
	Log Log `json:"log"`
}

global

package global

import (
	oplogging "github.com/op/go-logging"
	"github.com/spf13/viper"
	"go_Logger/config"
)

var (
	CONFIG config.Config
	VP     *viper.Viper
	LOG    *oplogging.Logger
)

 

读取

const defaultConfigFile = "config/config.yaml"

func init() {
	v := viper.New()
	v.SetConfigFile(defaultConfigFile)
	err := v.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	v.WatchConfig()

	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)
		if err := v.Unmarshal(&global.CONFIG); err != nil {
			fmt.Println(err)
		}
	})
	if err := v.Unmarshal(&global.CONFIG); err != nil {
		fmt.Println(err)
	}
	global.VP = v
}

 

  

 

Go语言读取各种配置文件

原文:https://www.cnblogs.com/zhangyafei/p/12863384.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!