1、main.go

package main

import (
	"fmt"
	"gin_demo/config"
	"gin_demo/routers"
	"github.com/gin-gonic/gin"
)

func main() {
	conf, err := config.ParseConfig("./config/app.json")
	if err != nil {
		panic("读取配置文件失败," + err.Error())
	}
	fmt.Printf("conf:%#v\n", conf)
	//创建一个默认的路由引擎
	engine := gin.Default()
	routers.RegisterRouter(engine)
	engine.Run(":9090")
}

2、config

     调用方式:config.GetConfig()

package config

import (
	"bufio"
	"encoding/json"
	"os"
)

type Config struct {
	AppName     string         `json:"app_name"`
	AppModel    string         `json:"app_model"`
	AppHost     string         `json:"app_host"`
	AppPort     string         `json:"app_port"`
	Database    DatabaseConfig `json:"database"`
	RedisConfig RedisConfig    `json:"redis_config"`
}

//数据库配置
type DatabaseConfig struct {
	Driver   string `json:"driver"`
	User     string `json:"user"`
	Password string `json:"password"`
	Host     string `json:"host"`
	Port     int    `json:"port"`
	DbName   string `json:"db_name"`
	Chartset string `json:"charset"`
	ShowSql  bool   `json:"show_sql"`
}

//Redis配置
type RedisConfig struct {
	Addr     string `json:"addr"`
	Port     int    `json:"port"`
	Password string `json:"password"`
	Db       int    `json:"db"`
}

//获取配置,外部使用"config.GetConfig()"调用
func GetConfig() *Config {
	return cfg
}

//存储配置的全局对象
var cfg *Config = nil

func ParseConfig(path string) (*Config, error) {
	file, err := os.Open(path) //读取文件
	defer file.Close()
	if err != nil {
		return nil, err
	}
	reader := bufio.NewReader(file)
	decoder := json.NewDecoder(reader) //解析json
	if err = decoder.Decode(&cfg); err != nil {
		return nil, err
	}
	return cfg, nil
}

3、app.json配置文件

{
  "app_name": "gin_demo",
  "app_model": "debug",
  "app_host": "localhost",
  "app_port": "9090",
  "database": {
    "driver": "mysql",
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "password": "123456",
    "db_name": "demo_go",
    "charset": "utf8",
    "show_sql": false
  },
  "redis_config": {
    "addr": "127.0.0.1",
    "port": 6379,
    "password": "123456",
    "db": 0
  }
}

4、在接口中输出整个配置:

type UserController struct {
}
func (controller *UserController) Get(context *gin.Context) {
	id := context.Query("id")
	context.JSON(http.StatusOK, gin.H{
		"id":   id,
		"conf": config.GetConfig(),
	})
}