配置文件結構體
config.go
package config
type System struct {
Mode string `mapstructure:"mode" json:"mode" ini:"mode"`
}
type Log struct {
Prefix string `mapstructure:"prefix" json:"prefix" ini:"prefix"`
LogFile bool `mapstructure:"log-file" json:"log-file" ini:"log-file" yaml:"log-file" toml:"log-file"`
Stdout string `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"`
}
全局配置
global.go
package global import "go_dev/go_read_config/config" var ( CONFIG = new(config.Config) )
一、讀取json
config.json
{
"system":{
"mode": "development"
},
"log": {
"prefix": "[MY-LOG] ",
"log-file": true,
"stdout": "DEBUG",
"file": "WARNING"
}
}
讀取配置
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)
}
二、讀取ini
config.ini
[system] mode='development' ;mode='production' [log] prefix='[MY-LOG] ' log-file=true stdout=DEBUG file=DEBUG
讀取
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)
}
三、讀取yaml
config.yaml
system: mode: 'development' log: prefix: '[MY-LOG] ' log-file: true stdout: 'DEBUG' file: 'DEBUG' mylog: level: 'debug' prefix: '[MY-LOG]' file_path: 'log' file_name: 'mylog.log' max_file_size: 10485760 max_age: 24
讀取
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)
}
四、讀取toml
config.toml
[system] mode = 'development' # mode = 'production' [log] prefix = "[MY-LOG] " log-file = true stdout = "DEBUG" file = "DEBUG"
讀取
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)
}
五、萬能的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
}
