The micro toolkit supports plugins for the binary itself. These are separate from go-micro plugins.
Plugins can be used to add flags, commands and middleware handlers. An example would be authentication, logging, tracing, etc. Existing plugins can be found in go-plugins/micro.
Here's a simple example of a plugin that adds a flag and then prints the value
Create a plugin.go file in the top level dir
package main
import (
"log"
"github.com/micro/cli"
"github.com/micro/micro/plugin"
)
func init() {
plugin.Register(plugin.NewPlugin(
plugin.WithName("example"),
plugin.WithFlag(cli.StringFlag{
Name: "example_flag",
Usage: "This is an example plugin flag",
EnvVar: "EXAMPLE_FLAG",
Value: "avalue",
}),
plugin.WithInit(func(ctx *cli.Context) error {
log.Println("Got value for example_flag", ctx.String("example_flag"))
return nil
}),
))
}
Simply build micro with the plugin
go build -o micro ./main.go ./plugin.go
Plugins can be added to go-micro in the following ways. By doing so they'll be available to set via command line args or environment variables.
import (
"github.com/micro/go-micro/cmd"
_ "github.com/micro/go-plugins/broker/rabbitmq"
_ "github.com/micro/go-plugins/registry/kubernetes"
_ "github.com/micro/go-plugins/transport/nats"
)
func main() {
// Parse CLI flags
cmd.Init()
}
The same is achieved when calling service.Init
import (
"github.com/micro/go-micro"
_ "github.com/micro/go-plugins/broker/rabbitmq"
_ "github.com/micro/go-plugins/registry/kubernetes"
_ "github.com/micro/go-plugins/transport/nats"
)
func main() {
service := micro.NewService(
// Set service name
micro.Name("my.service"),
)
// Parse CLI flags
service.Init()
}
Activate via a command line flag
go run service.go --broker=rabbitmq --registry=kubernetes --transport=nats
CLI Flags provide a simple way to initialise plugins but you can do the same yourself.
import (
"github.com/micro/go-micro"
"github.com/micro/go-plugins/registry/kubernetes"
)
func main() {
registry := kubernetes.NewRegistry() //a default to using env vars for master API
service := micro.NewService(
// Set service name
micro.Name("my.service"),
// Set service registry
micro.Registry(registry),
)
}
You may want to swap out plugins using automation or add plugins to the micro toolkit. An easy way to do this is by maintaining a separate file for plugin imports and including it during the build.
Create file plugins.go
package main
import (
_ "github.com/micro/go-plugins/broker/rabbitmq"
_ "github.com/micro/go-plugins/registry/kubernetes"
_ "github.com/micro/go-plugins/transport/nats"
)
Build with plugins.go
go build -o service main.go plugins.go
Run with plugins
service --broker=rabbitmq --registry=kubernetes --transport=nats