Go语言读取各种配置文件
<h4>配置文件结构体</h4><p>config.go</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">package config
type System struct {
Mode string `mapstructure:"mode" json:"mode" ini:"mode"`
}
type Log struct {
Prefixstring `mapstructure:"prefix" json:"prefix" ini:"prefix"`
LogFile bool `mapstructure:"log-file" json:"log-file" ini:"log-file" yaml:"log-file" toml:"log-file"`
Stdoutstring `mapstructure:"stdout" json:"stdout" ini:"stdout"`
File string `mapstructure:"file" json:"file" ini:"file"`
}
type Config struct {
System System `json:"system" ini:"system"`
Log Log `json:"log" ini:"log"`
}</pre>
</div>
<h4>全局配置</h4>
<p>global.go</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">package global
import "go_dev/go_read_config/config"
var (
CONFIG = new(config.Config)
)</pre>
</div>
<h3>一、读取json</h3>
<p>config.json</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">{
"system":{
"mode": "development"
},
"log": {
"prefix": " ",
"log-file": true,
"stdout": "DEBUG",
"file": "WARNING"
}
}</pre>
</div>
<p>读取配置</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">package initialize
import (
"encoding/json"
"fmt"
"go_dev/go_read_config/global"
"os"
)
func InitConfigFromJson() {
// 打开文件
file, _ := os.Open("config.json")
// 关闭文件
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)
}
fmt.Println(global.CONFIG)
}</pre>
</div>
<h3>二、读取ini</h3>
<h4> config.ini</h4>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">
mode='development'
;mode='production'
prefix=' '
log-file=true
stdout=DEBUG
file=DEBUG</pre>
</div>
<p>读取</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">package initialize
import (
"fmt"
"github.com/go-ini/ini"
"go_dev/go_read_config/global"
"log"
)
func InitConfigFromIni() {
err := ini.MapTo(global.CONFIG, "config.ini")
if err != nil {
log.Println(err)
return
}
fmt.Println(global.CONFIG)
}</pre>
</div>
<h3>三、读取yaml</h3>
<p>config.yaml</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">system:
mode: 'development'
log:
prefix: ' '
log-file: true
stdout: 'DEBUG'
file: 'DEBUG'
mylog:
level: 'debug'
prefix: ''
file_path: 'log'
file_name: 'mylog.log'
max_file_size: 10485760
max_age: 24</pre>
</div>
<p>读取</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">package initialize
import (
"fmt"
"go_dev/go_read_config/global"
"gopkg.in/yaml.v2"
"io/ioutil"
)
func IniConfigFromYaml(){
file, err := ioutil.ReadFile("config.yaml")
if err != nil {
panic(err)
}
err = yaml.Unmarshal(file, global.CONFIG)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(global.CONFIG)
}</pre>
</div>
<h3>四、读取toml</h3>
<p>config.toml</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">
mode = 'development'
# mode = 'production'
prefix = " "
log-file = true
stdout = "DEBUG"
file = "DEBUG"</pre>
</div>
<p>读取</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">import (
"fmt"
"github.com/BurntSushi/toml"
"go_dev/go_read_config/global"
)
func InitConfigFromToml() {
_, err := toml.DecodeFile("config.toml", global.CONFIG)
if err != nil {
panic(err)
}
fmt.Println(global.CONFIG)
}</pre>
</div>
<h3>五、万能的viper</h3>
<p>Viper是一个方便Go语言应用程序处理配置信息的库。它可以处理多种格式的配置。它支持的特性:</p>
<ul>
<li>设置默认值</li>
<li>从JSON、TOML、YAML、HCL和Java properties文件中读取配置数据</li>
<li>可以监视配置文件的变动、重新读取配置文件</li>
<li>从环境变量中读取配置数据</li>
<li>从远端配置系统中读取数据,并监视它们(比如etcd、Consul)</li>
<li>从命令参数中读物配置</li>
<li>从buffer中读取</li>
<li>调用函数设置配置信息</li>
</ul>
<p>config.json</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">#json文件
{
"appId": "123456789",
"secret": "maple123456",
"host": {
"address": "localhost",
"port": 5799
}
}</pre>
</div>
<p>读取</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">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)
</pre>
</div>
<p>config.yaml</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">log:
prefix: ' '
log-file: true
stdout: 'DEBUG'
file: 'DEBUG'</pre>
</div>
<p>config.go</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">type Log struct {
Prefixstring `mapstructure:"prefix" json:"prefix"`
LogFile bool `mapstructure:"log-file" json:"logFile"`
Stdoutstring `mapstructure:"stdout" json:"stdout"`
File string `mapstructure:"file" json:"file"`
}
type Config struct {
Log Log `json:"log"`
}
</pre>
</div>
<p>global</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">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
)</pre>
</div>
<p> </p>
<p>读取</p>
<div class="cnblogs_Highlighter">
<pre class="brush:go;gutter:true;">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
}
</pre>
</div>
<p> </p>
<p> </p>
<p> </p>
</div>
<div id="MySignature" role="contentinfo">
<div style="border-bottom: #e0e0e0 1px dashed; border-left: #e0e0e0 1px dashed; padding: 10px; font-family: 微软雅黑; font-size: 11px; border-top: #e0e0e0 1px dashed; border-right: #e0e0e0 1px dashed;overflow: hidden;" id="PSignature">
<div style="float: left; width: 10%">
<img src="https://www.cnblogs.com/images/cnblogs_com/zhangyafei/1378866/o_o_Warning.png" style="width: 70px; height: 70px">
</div>
<div style="float: left; width: 90%; padding-top: 10px">
作者:张亚飞 <br>
出处:https://www.cnblogs.com/zhangyafei <br>
gitee:https://gitee.com/zhangyafeii <br>
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。<br>
</div>
</div><br><br>
来源:https://www.cnblogs.com/zhangyafei/p/12863384.html
頁:
[1]