From 1b165a662894c6aba9fa7d4c5e21bb87aac55c11 Mon Sep 17 00:00:00 2001 From: Michael Ding Date: Tue, 5 Nov 2019 15:55:12 +0800 Subject: [PATCH] add createapp --- app.go | 58 ++++++++++++++++++---------------------------------------- 1 file changed, 18 insertions(+), 40 deletions(-) diff --git a/app.go b/app.go index 7b74d554..367d2fcb 100644 --- a/app.go +++ b/app.go @@ -21,8 +21,8 @@ type Extention interface { // Application struct type Application struct { - RootPath string - Env string + rootPath string + env string config *viper.Viper extentions map[Key]Extention initialized bool @@ -48,42 +48,6 @@ func (d *Application) GetOK(key Key) (Extention, bool) { return ext, ok } -// Set the extention at the specified key -func (d *Application) Set(key Key, ext Extention) error { - d.mu.Lock() - defer d.mu.Unlock() - - if d.initialized { - return fmt.Errorf("can't be called after app initialized") - } - - if d.extentions == nil { - d.extentions = make(map[Key]Extention) - } - - d.extentions[key] = ext - return nil -} - -// SetMany set many extentions once. values will be override if same key occurred -func (d *Application) SetMany(exts map[Key]Extention) error { - d.mu.Lock() - defer d.mu.Unlock() - - if d.initialized { - return fmt.Errorf("can't be called after app initialized") - } - - if d.extentions == nil { - d.extentions = make(map[Key]Extention, len(exts)) - } - - for k, v := range exts { - d.extentions[k] = v - } - return nil -} - // Config returns the viper config for this application func (d *Application) Config() *viper.Viper { return d.config @@ -109,13 +73,13 @@ func (d *Application) Init() error { } func (d *Application) initConfig() error { - configfile := filepath.Join(d.RootPath, "config.yaml") + configfile := filepath.Join(d.rootPath, "config.yaml") config := viper.New() config.SetConfigFile(configfile) if err := config.ReadInConfig(); err != nil { return err } - config = config.Sub(d.Env) + config = config.Sub(d.env) // add default config config.SetDefault("debug", false) @@ -167,3 +131,17 @@ func (d *Application) closeExtentions() error { } return nil } + +// CreateApp create an gobay Application +func CreateApp(rootPath string, env string, exts map[Key]Extention) (*Application, error) { + if rootPath == "" || env == "" { + return nil, fmt.Errorf("lack of rootPath or env") + } + + app := &Application{rootPath: rootPath, env: env, extentions: exts} + + if err := app.Init(); err != nil { + return nil, err + } + return app, nil +}