插件机制

Nirvana 的 Config 除了使用 Configurer 配置基本信息以外,还提供了插件机制。

插件接口:

  1. // ConfigInstaller is used to install config to service builder.
  2. type ConfigInstaller interface {
  3. // Name is the external config name.
  4. Name() string
  5. // Install installs stuffs before server starting.
  6. Install(builder service.Builder, config *Config) error
  7. // Uninstall uninstalls stuffs after server terminating.
  8. Uninstall(builder service.Builder, config *Config) error
  9. }

插件实现了这个接口之后,即可通过 nirvana 包提供的方法进行注册:

  1. func RegisterConfigInstaller(ci ConfigInstaller)

一般情况下,插件应该通过插件 package 的 init() 进行注册。然后提供相应的 Configurer 在 Nirvana 的 Config 中添加插件配置。

Plugin Framework

一个基本的插件框架如下:

  1. func init() {
  2. // Register your config installer into nirvana.
  3. nirvana.RegisterConfigInstaller(&pluginInstaller{})
  4. }
  5. // ExternalConfigName is the external config name for your plugin. Please ensure that the
  6. // name is unique and won't conflict with other plugins.
  7. const ExternalConfigName = "pluginName"
  8. type pluginInstaller struct{}
  9. // Name is the external config name.
  10. func (i *pluginInstaller) Name() string {
  11. return ExternalConfigName
  12. }
  13. // Install installs config to builder. You can get plugin config from nirvana config. Then
  14. // install/initialize what you need.
  15. func (i *pluginInstaller) Install(builder service.Builder, cfg *nirvana.Config) error {...}
  16. // Uninstall uninstalls stuffs after server terminating.
  17. func (i *pluginInstaller) Uninstall(builder service.Builder, cfg *nirvana.Config) error {...)
  18. // ConfigA configures fieldA. Be careful, you should get/save plugin config into nirvana config
  19. // by `c.Config(ExternalConfigName)`/`c.Set(ExternalConfigName, cfg)` rather than a global
  20. // plugin config.
  21. func ConfigA(fieldA FieldType) nirvana.Configurer {...}
  22. // ConfigB configures fieldB.
  23. func ConfigB() nirvana.Configurer {...}
  24. // Disable returns a configurer to disable current plugin for a certain nirvana server.
  25. func Disable() nirvana.Configurer {
  26. return func(c *nirvana.Config) error {
  27. // Set to nil will delete plugin config from nirvana config.
  28. c.Set(ExternalConfigName, nil)
  29. return nil
  30. }
  31. }