Golang 入门系列(九) 如何读取YAML,JSON,INI等配置文件
实际项目中,读取相关的系统配置文件是很常见的事情。今天就来说一说,Golang 是如何读取YAML,JSON,INI等配置文件的。 1. json使用 JSON 应该比较熟悉,它是一种轻量级的数据交换格式。层次结构简洁清晰 ,易于阅读和编写,同时也易于机器解析和生成。 1. 创建 conf.json: { "enabled": true, "path": "/usr/local" } 2. 新建config_json.go: package main import ( "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(...