golang读取json配置文件

本文将描述使用 "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)
}

实际输出

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值