github.com/zly-app/zapp@v1.3.3/plugin.go (about)

     1  /*
     2  -------------------------------------------------
     3     Author :       zlyuancn
     4     date:         2021/1/20
     5     Description :
     6  -------------------------------------------------
     7  */
     8  
     9  package zapp
    10  
    11  import (
    12  	"go.uber.org/zap"
    13  
    14  	"github.com/zly-app/zapp/core"
    15  	"github.com/zly-app/zapp/logger"
    16  	"github.com/zly-app/zapp/plugin"
    17  )
    18  
    19  // 初始化插件
    20  func (app *appCli) makePlugin() {
    21  	err := app.opt.CheckPlugins(app)
    22  	if err != nil {
    23  		app.Fatal("插件检查失败", zap.Error(err))
    24  	}
    25  
    26  	for _, pluginType := range app.opt.Plugins {
    27  		app.plugins[pluginType] = plugin.MakePlugin(app, pluginType)
    28  	}
    29  }
    30  
    31  func (app *appCli) startPlugin() {
    32  	app.Debug("启动插件")
    33  	for _, pluginType := range app.opt.Plugins {
    34  		p, ok := app.plugins[pluginType]
    35  		if !ok {
    36  			app.Fatal("插件查找失败", zap.String("pluginType", string(pluginType)))
    37  		}
    38  
    39  		err := p.Start()
    40  		if err != nil {
    41  			app.Fatal("插件启动失败", zap.String("pluginType", string(pluginType)), zap.Error(err))
    42  		}
    43  	}
    44  }
    45  
    46  func (app *appCli) closePlugin() {
    47  	app.Debug("关闭插件")
    48  	for _, pluginType := range app.opt.Plugins {
    49  		p, ok := app.plugins[pluginType]
    50  		if !ok {
    51  			app.Fatal("插件查找失败", zap.String("pluginType", string(pluginType)))
    52  		}
    53  
    54  		if err := p.Close(); err != nil {
    55  			app.Error("插件关闭失败", zap.String("pluginType", string(pluginType)), zap.Error(err))
    56  		}
    57  	}
    58  }
    59  
    60  func (app *appCli) GetPlugin(pluginType core.PluginType) (core.IPlugin, bool) {
    61  	p, ok := app.plugins[pluginType]
    62  	return p, ok
    63  }
    64  
    65  func (app *appCli) InjectPlugin(pluginType core.PluginType, a ...interface{}) {
    66  	p, ok := app.GetPlugin(pluginType)
    67  	if !ok {
    68  		if app.opt.IgnoreInjectOfDisablePlugin {
    69  			return
    70  		}
    71  		logger.Log.Fatal("注入失败, 未启用插件", zap.String("pluginType", string(pluginType)))
    72  	}
    73  
    74  	p.Inject(a...)
    75  }