github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/plugin/README.md (about) 1 # Plugins 2 3 Plugins are a way of extending the functionality of Micro 4 5 ## Overview 6 7 Plugins enable Micro to be extending and intercepted to provide additional functionality and features. 8 This may include logging, metrics, tracing, authentication, etc. The Plugin model requires registering 9 a struct that matches a plugin interface. It's then registered and setup when Micro starts. 10 11 ## Design 12 13 Here's the interface design 14 15 ```go 16 // Plugin is the interface for plugins to micro. It differs from go-micro in that it's for 17 // the micro API, Web, Sidecar, CLI. It's a method of building middleware for the HTTP side. 18 type Plugin interface { 19 // Global Flags 20 Flags() []cli.Flag 21 // Sub-commands 22 Commands() []cli.Command 23 // Handle is the middleware handler for HTTP requests. We pass in 24 // the existing handler so it can be wrapped to create a call chain. 25 Handler() Handler 26 // Init called when command line args are parsed. 27 // The initialised cli.Context is passed in. 28 Init(*cli.Context) error 29 // Name of the plugin 30 String() string 31 } 32 33 // Manager is the plugin manager which stores plugins and allows them to be retrieved. 34 // This is used by all the components of micro. 35 type Manager interface { 36 Plugins() map[string]Plugin 37 Register(name string, plugin Plugin) error 38 } 39 40 // Handler is the plugin middleware handler which wraps an existing http.Handler passed in. 41 // Its the responsibility of the Handler to call the next http.Handler in the chain. 42 type Handler func(http.Handler) http.Handler 43 ``` 44 45 ## How to use it 46 47 Here's a simple example of a plugin that adds a flag and then prints the value 48 49 ### The plugin 50 51 Create a plugin.go file in the top level dir 52 53 ```go 54 package main 55 56 import ( 57 "log" 58 "github.com/urfave/cli/v2" 59 "github.com/tickoalcantara12/micro/plugin" 60 ) 61 62 func init() { 63 plugin.Register(plugin.NewPlugin( 64 plugin.WithName("example"), 65 plugin.WithFlag(&cli.StringFlag{ 66 Name: "example_flag", 67 Usage: "This is an example plugin flag", 68 EnvVars: []string{"EXAMPLE_FLAG"}, 69 Value: "avalue", 70 }), 71 plugin.WithInit(func(ctx *cli.Context) error { 72 log.Println("Got value for example_flag", ctx.String("example_flag")) 73 return nil 74 }), 75 )) 76 } 77 ``` 78 79 ### Building the code 80 81 Simply build micro with the plugin 82 83 ```shell 84 go build -o micro ./main.go ./plugin.go 85 ``` 86