Runtime Plugins

Plugins are a way of integrating external code into the Micro toolkit. This is completely separate to go-micro plugins. Using plugins here allows you to add additional flags, commands and HTTP handlers to the toolkit.

How it works

There is a global plugin manager under micro/plugin which consists of plugins that will be used across the entire toolkit. Plugins can be registered by calling plugin.Register. Each component (api, web, proxy, cli, bot) has a separate plugin manager used to register plugins which should only be added as part of that component. They can be used in the same way by called api.Register, web.Register, etc.

Here’s the interface

  1. // Plugin is the interface for plugins to micro. It differs from go-micro in that it's for
  2. // the micro API, Web, Proxy, CLI. It's a method of building middleware for the HTTP side.
  3. type Plugin interface {
  4. // Global Flags
  5. Flags() []cli.Flag
  6. // Sub-commands
  7. Commands() []cli.Command
  8. // Handle is the middleware handler for HTTP requests. We pass in
  9. // the existing handler so it can be wrapped to create a call chain.
  10. Handler() Handler
  11. // Init called when command line args are parsed.
  12. // The initialised cli.Context is passed in.
  13. Init(*cli.Context) error
  14. // Name of the plugin
  15. String() string
  16. }
  17. // Manager is the plugin manager which stores plugins and allows them to be retrieved.
  18. // This is used by all the components of micro.
  19. type Manager interface {
  20. Plugins() map[string]Plugin
  21. Register(name string, plugin Plugin) error
  22. }
  23. // Handler is the plugin middleware handler which wraps an existing http.Handler passed in.
  24. // Its the responsibility of the Handler to call the next http.Handler in the chain.
  25. type Handler func(http.Handler) http.Handler

How to use it

Here’s a simple example of a plugin that adds a flag and then prints the value

The plugin

Create a plugin.go file in the top level dir

  1. package main
  2. import (
  3. "log"
  4. "github.com/micro/cli"
  5. "github.com/micro/micro/plugin"
  6. )
  7. func init() {
  8. plugin.Register(plugin.NewPlugin(
  9. plugin.WithName("example"),
  10. plugin.WithFlag(cli.StringFlag{
  11. Name: "example_flag",
  12. Usage: "This is an example plugin flag",
  13. EnvVar: "EXAMPLE_FLAG",
  14. Value: "avalue",
  15. }),
  16. plugin.WithInit(func(ctx *cli.Context) error {
  17. log.Println("Got value for example_flag", ctx.String("example_flag"))
  18. return nil
  19. }),
  20. ))
  21. }

Building the code

Simply build micro with the plugin

  1. go build -o micro ./main.go ./plugin.go

Repository

The plugins for the toolkit can be found in github.com/micro/go-plugins/micro.