跳转至

config

简介

  • ie310go不提供复杂的配置系统
  • 仅提供简单json解析,下文演示如何使用:

AppConfig类

  • 首先,需要定义一个AppConfig类:
    //AppConfig ..
    type AppConfig struct {
        Port           string
        ServiceSuffix  string
        Jsonp          bool
        LogArgs        bool
        Appkey         string
        StaticFilePath string
        RiotIndexPath  string
        DataBase       gosql.Config
        DataBaseRO     gosql.Config
        RedisURL       string
    }
    

appconfig.json文件

  • 然后,需要定义对应的json文件appconfig.json:
    {
        "Port": "8083",
        "AdminPort": "8084",
        "ServiceSuffix": "goss",
        "Jsonp": true,
        "LogArgs": false,
        "Appkey": "i3work_goservcie",
        "RedisURL": "127.0.0.1:6379",
        "StaticFilePath": "",
        "RiotIndexPath": "",
        "DataBase": {
            "enable": true,
            "driver": "mysql",
            "dsn": "username:password@tcp(server:ip)/dbname?charset=utf8&parseTime=True&loc=Asia%2FShanghai",
            "show_sql": true,
            "max_open_conns": 20,
            "max_idle_conns": 20,
            "max_life_time": 3600
        },
        "DataBaseRO": {
            "enable": true,
            "driver": "mysql",
            "dsn": "username:password@tcp(server:ip)/dbname?charset=utf8&parseTime=True&loc=Asia%2FShanghai",
            "show_sql": true,
            "max_open_conns": 20,
            "max_idle_conns": 20,
            "max_life_time": 3600
        }
    }
    

解析

  • 通过以下代码即可将json文件解析到Config类中:
    package config
    
    import (
        "github.com/ie310mu/ie310go/config"
    )
    
    // Config ...
    var Config AppConfig
    
    // Init ...
    func Init(file string) AppConfig {
        config.ScanFromFile(file, &Config)
        return Config
    }
    
  • 调用时,可结合命令行参数动态指定配置文件位置
    调试时无此参数默认使用根目录下配置,测试或生产环境中可通过命令行参数指定实际使用的配置文件的位置:
        //import cu "i3work/config"   
    
        configFileName := "appconfig.json"
        for _, arg := range os.Args {
            if strings.Index(arg, "-cf ") == 0 { //配置文件
                fileName := arg[4:]
                fileName = strings.Trim(fileName, "")
                configFileName = fileName
            }
        }
        cfg := cu.Init(configFileName)
    
    注:上述代码是通过解析os.Args来解析命令行参数,更好的做法是通过flag来自动解析

其他

  • 上文只是一种实现方式的示例,实际上可使用任意实现方式以满足项目需求
  • 可以结合flag命令行参数使用
  • 可以使用toml(类似于ini配置)