美文网首页Golang
beego源码(1) 配置加载

beego源码(1) 配置加载

作者: Linrundong | 来源:发表于2019-02-15 17:22 被阅读4次

    beego.init()启动初始化

    • 默认配置对象:
      BConfig *Config
    • 自定义配置对象:
      AppConfig *beegoAppConfig
    func init() {
        // 加载默认配置
        BConfig = newBConfig()
    
        // 确定配置文件路径
        var filename = "app.conf"
        appConfigPath = filepath.Join(workPath, "conf", filename)
        
        // 加载配置文件
        if err = parseConfig(appConfigPath); err != nil {
            panic(err)
        }
    }
    

    BConfig 默认配置

    func newBConfig() *Config {
        return &Config{
            AppName:             "beego",
            RunMode:             PROD,
            RouterCaseSensitive: true,
            ServerName:          "beegoServer:" + VERSION,
            RecoverPanic:        true,
            RecoverFunc:         recoverPanic,
            CopyRequestBody:     false,
            EnableGzip:          false,
            MaxMemory:           1 << 26, //64MB
            EnableErrorsShow:    true,
            EnableErrorsRender:  true,
            Listen: Listen{
                ...
            },
            WebConfig: WebConfig{
                ...
            },
            Log: LogConfig{
                ...
            },
        }
    }
    
    • 默认填写了一些信息,还有Listen、WebConfig、Log几个方面的配置
    • 重点关注RunMode 这项:根据DEV、PROD等可区分开发、生产不同环境的配置

    AppConfig 用户配置

    • appConfigProvider默认值是"ini",意味着默认读取的是ini配置格式
    • assignConfig()主要创建了一个config对象,实例化时通过config包的Init(),调用config/ini.go的Parse()把配置项进行加载
    type beegoAppConfig struct {
        // 这里beegoAppConfig这个对象继承了config包中的Configer对象
        innerConfig config.Configer
    }
    
    func NewConfig(adapterName, filename string) (Configer, error) {
        // 获取指定格式的配置器
        adapter, ok := adapters[adapterName]
        if !ok {
            return nil, fmt.Errorf("config: unknown adaptername %q (forgotten import?)", adapterName)
        }
        // 加载配置项
        return adapter.Parse(filename)
    }
    
    // 这里传入了配置格式,文件路径
    func newAppConfig(appConfigProvider, appConfigPath string) (*beegoAppConfig, error) {
        // 默认返回ini格式的config对象
        ac, err := config.NewConfig(appConfigProvider, appConfigPath)
        if err != nil {
            return nil, err
        }
        return &beegoAppConfig{ac}, nil
    }
    
    // now only support ini, next will support json.
    func parseConfig(appConfigPath string) (err error) {
        AppConfig, err = newAppConfig(appConfigProvider, appConfigPath)
        if err != nil {
            return err
        }
        return assignConfig(AppConfig)
    }
    
    • 执行完毕配置文件中的配置已存在于AppConfig中
    关于beego/config
    • config.png
    • config包内xml.go、yaml.go、ini.go、json.go文件中都有自己的init(),所以导入config包时就已生成了这四种格式的配置器
    • config.NewConfig(appConfigProvider, appConfigPath)调用时相当于获取对应格式的配置器

    相关文章

      网友评论

        本文标题:beego源码(1) 配置加载

        本文链接:https://www.haomeiwen.com/subject/pgemeqtx.html