
文章插图
实际项目中,还有一个比较重要的基础功能,就是读取相关的配置文件 。今天就来说一说,Golang 是如何读取YAML,JSON,INI等配置文件的 。
1. json使用
JSON 应该比较熟悉,它是一种轻量级的数据交换格式 。层次结构简洁清晰 ,易于阅读和编写,同时也易于机器解析和生成 。
1. 创建 conf.json:
{
"enabled": true,
"path": "/usr/local"
}
2. 新建config_json.go:
package mainimport ( "encoding/json" "fmt" "os")type configuration struct { Enabled bool Path string}func main() { // 打开文件 file, _ := os.Open("conf.json") // 关闭文件 defer file.Close() //NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据 。decoder := json.NewDecoder(file) conf := configuration{} //Decode从输入流读取下一个json编码值并保存在v指向的值里 err := decoder.Decode(&conf) if err != nil { fmt.Println("Error:", err) } fmt.Println("path:" + conf.Path)}启动运行后,输出如下:
D:Go_Pathgosrcconfigmgr>go run config_json.gopath:/usr/local2. ini的使用
INI文件格式是某些平台或软件上的配置文件的非正式标准,由节(section)和键(key)构成,比较常用于微软windows操作系统中 。这种配置文件的文件扩展名为INI 。
1. 创建 conf.ini:
[Section]enabled = truepath = /usr/local # another comment
【如何读取yaml,json,ini等配置文件】2.下载第三方库:go get gopkg.in/gcfg.v1
3. 新建 config_ini.go:
package mainimport ( "fmt" gcfg "gopkg.in/gcfg.v1")func main() { config := struct { Section struct { Enabled bool Path string } }{} err := gcfg.ReadFileInto(&config, "conf.ini") if err != nil { fmt.Println("Failed to parse config file: %s", err) } fmt.Println(config.Section.Enabled) fmt.Println(config.Section.Path)}启动运行后,输出如下:
D:Go_Pathgosrcconfigmgr>go run config_ini.gotrue/usr/local3. yaml使用
yaml 可能比较陌生一点,但是最近却越来越流行 。也就是一种标记语言 。层次结构也特别简洁清晰 ,易于阅读和编写,同时也易于机器解析和生成 。
golang的标准库中暂时没有给我们提供操作yaml的标准库,但是github上有很多优秀的第三方库开源给我们使用 。
1. 创建 conf.yaml:
enabled: truepath: /usr/local2. 下载第三方库:go get gopkg.in/yaml.v2
3. 创建 config_yaml.go:
package mainimport ( "fmt" "io/ioutil" "log" "gopkg.in/yaml.v2")type conf struct { Enabled bool `yaml:"enabled"` //yaml:yaml格式 enabled:属性的为enabled Path string `yaml:"path"`}func (c *conf) getConf() *conf { yamlFile, err := ioutil.ReadFile("conf.yaml") if err != nil { log.Printf("yamlFile.Get err #%v ", err) } err = yaml.Unmarshal(yamlFile, c) if err != nil { log.Fatalf("Unmarshal: %v", err) } return c}func main() { var c conf c.getConf() fmt.Println("path:" + c.Path)}启动运行后,输出如下:
D:Go_Pathgosrcconfigmgr>go run config_yaml.gopath:/usr/local
推荐阅读
-
运势|从8月13日开始,运势真好,会鸿运当头,福财兼收的三大生肖
-
苹果笔记本电脑原装电池多少钱 苹果macbookpro原装电池多少钱
-
高考673分学霸,高二就被清华大学签约,在望子成龙学校学习7年多
-
央视新闻客户端|苏里南重新恢复严格防控新冠肺炎疫情措施
-
长沙交通音乐广播|手抖加了个“0”?!千万房产拍成1.65亿!还有更乌龙的…
-
北京暴雨|今天午后北京将迎明显降雨 夜间雨势强劲局地有暴雨
-
-
毛巾|旧袜子旧内衣竟是毛巾生产原料!年产毛巾50亿条都销往了哪里?
-
「我的第一部5G手机」「园区」新基建语境下 5G园区如何迸发产业机遇
-
-
家校共育家长讲话稿?家校协力共育未来家长会发言稿_1
-
江苏再迎新高铁,估算投资1000亿,推动扬子江城市群融合联动发展
-
-
-
【娱见现实|岳云鹏录制节目划水被赞佛系?现在的观众好仁慈!】
-
生米煮成熟饭|在这个季节,逛街穿什么衣服显瘦,微胖型的三十多岁“女教师”
-
-
圆圆的橘子味|国庆中秋假期即将来了!双节你们公司到底安排了什么福利呢
-
-