Go语言读取各种配置文件
配置文件结构体
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
}
Go语言读取各种配置文件的更多相关文章
- 读取HeidiSQL 配置文件中的密码
读取HeidiSQL 配置文件中的密码 2017-1-21 5:42:01 codegay HeidiSQL是一款开源的SQL管理工具,用管理MYSQL,MSSQL 等数据库, 很多管理工具都会把密码 ...
- SpringBoot中如何优雅的读取yml配置文件?
YAML是一种简洁的非标记语言,以数据为中心,使用空白.缩进.分行组织数据,从而使得表示更加简洁易读.本文介绍下YAML的语法和SpringBoot读取该类型配置文件的过程. 本文目录 一.YAML基 ...
- 在spring boot使用总结(九) 使用yaml语言来写配置文件
yaml是专门用来写配置文件的语言.使用yaml来写配置文件扩展性比较强而且十分方便.spring boot支持使用yaml语言来写配置文件,使用snakeyaml库来读取配置文件.spring bo ...
- 读取.properties配置文件
方法1 public class SSOUtils { protected static String URL_LOGIN = "/uas/service/api/login/info&q ...
- java读取properties配置文件总结
java读取properties配置文件总结 在日常项目开发和学习中,我们不免会经常用到.propeties配置文件,例如数据库c3p0连接池的配置等.而我们经常读取配置文件的方法有以下两种: (1) ...
- 【XML配置文件读取】使用jdom读取XML配置文件信息
在项目中我们经常需要将配置信息写在配置文件中,而XML配置文件是常用的格式. 下面将介绍如何通过jdom来读取xml配置文件信息. 配置文件信息 <?xml version="1.0& ...
- Web 项目 中读取专用配置文件
在 web 开发中,有时我们要为 业务逻辑处理 配置专用的 配置文件,也就是 xml 文件,这样可以极大的方便维护工作,但是读取 专用的配置文件还需要自己写一个方法,在这里,我封装了一个公用 的方法: ...
- Java读取Properties配置文件
1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了Map接口,使用键值对的形式来保存属性集.不过Properties的键和值都是字符串 ...
- spring读取prperties配置文件(2)
接上篇,spring读取prperties配置文件(1),这一篇主要讲述spring如何用annotation的方式去读取自定义的配置文件. 这里我先定义好属性文件"user.propert ...
随机推荐
- python f-strings !表达式
近期看一些框架的文档时发现, python的f-strings有f"{xxx!r}"的写法, 就官网看了一波文档, 特此记录一下, 顺便完善一下f-strings的使用 f-str ...
- Boss直聘App上“天使投资、VC、PE” 与“A轮、B轮、C轮融资”的关系
我们经常看到朋友圈里某某公司获得了某轮融资,所谓的A轮B轮究竟是个什么概念呢?今天就跟小伙伴们分享一下A.B.C.D轮融资与天使投资.VC.PE的关系. 天使投资(AI):天使投资所投的是一些非常早期 ...
- 2、Redis的安装
一.Windows下Redis安装 下载地址 Redis中文网站 Github地址 1.将下载下来的文件解压到目录 2.双击redis-server.exe运行 出现如下界面证明运行成功 3.双击 ...
- GDB调试增强篇
GDB中应该知道的几个调试方法 七.八年前写过一篇<用GDB调试程序>, 于是,从那以后,很多朋友在MSN上以及给我发邮件询问我关于GDB的问题,一直到今天,还有人在问GDB的相关问题.这 ...
- 【Web】BUUCTF-warmup(CVE-2018-12613)
BUUCTF 的第一题,上来就给搞懵了.. .这要是我自己做出来的,岂不是相当于挖了一个 CVE ?(菜鸡这样安慰自己) 问题在 index.php 的 55~63 行 // If we have ...
- 11 - Vue3 UI Framework - Card 组件
卡片是非常常用也是非常重要的组件,特别是在移动端的众多应用场景中,随便打开一个手机 App ,您会发现充斥着各种各样的卡片. 所以,我们也来制作一个简易的 Card 组件 返回阅读列表点击 这里 需求 ...
- CF140D New Year Contest 题解
Content 小 G 想打一场跨年比赛,比赛从下午 \(18:00\) 开始一直持续到次日清晨 \(6:00\),一共有 \(n\) 道题目.小 G 在比赛开始之前需要花费 10 分钟考虑这些题目的 ...
- IO复用的三种方法(select,poll,epoll)深入理解
(一)IO复用是Linux中的IO模型之一,IO复用就是进程告诉内核需要监视的IO条件,使得内核一旦发现进程指定的一个或多个IO条件就绪,就通过进程处理,从而不会在单个IO上阻塞了,Linux中,提供 ...
- SpringBoot(SpringMVC)使用addViewControllers设置统一请求URL重定向配置
只需要在配置中重写 addViewControllers方法 import org.springframework.context.annotation.Configuration; import o ...
- MIUI12.5扫码之后无法连接MIUI+,显示连接失败
设置-应用设置-应用管理-小米互联通信服务(如果没有找到,进行搜索即可)-清除数据 重新扫码连接就可以连上了 (感觉不怎么样,不知道是不是我网卡,用起来卡卡的...)