本文将描述使用 "encoding/json"
包对json 配置文件进行解析的方法
项目目录
src
├── config
| ├──app.json #(存放配置的json)
| └── ...
├── tool
| ├──config.go #(解析json的文件)
| └── ...
├── main.go #(主程序入口)
具体内容
app.json 文件
{
"app_name": "myblog",
"app_mode": "debug",
"app_host": "localhost",
"app_port": "8090",
"db": {
"db_user": "root",
"db_pass": "123456",
"db_addr": "localhost",
"db_port": "3306",
"db_table": "test"
}
}
config.go
在config.go中 将完成对于json 的解析工作,我们会使用到init方法,在main函数执行之前完成文件的读取,并赋值到Config 结构体对象之中。
package tool
import (
"encoding/json"
"fmt"
"os"
)
type DB struct {
DbUser string `json:"db_user"`
DbPass string `json:"db_pass"`
DbAddr string `json:"db_addr"`
DbPort string `json:"db_port"`
DbTable string `json:"db_table"`
}
type CONFIG struct {
AppName string `json:"app_name"`
AppMode string `json:"app_mode"`
AppHost string `json:"app_host"`
AppPort string `json:"app_port"`
Db DB `json:"db"`
}
var Config CONFIG
/* 利用init 函数会在主函数执行之前运行的特点,在main函数执行之前读取文件 */
func init() {
// 打开文件
file, _ := os.Open("./config/app.json")
// 关闭文件
defer file.Close()
// NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据。
decoder := json.NewDecoder(file)
//Decode从输入流读取下一个json编码值并保存在v指向的值里
err := decoder.Decode(&Config)
if err != nil {
panic(err)
}
fmt.Println(Config)
}
main.go
package main
import (
"fmt"
. "ni_blog/tool"
)
func main() {
fmt.Print(Config.AppPort)
}