Go Micro 插件 plugin

Go Micro plugin 会在每次调用服务的都会触发,根据注册的顺序进行调用,它的作用可以理解为拦截器。可以利用 plugin 实现拦截功能,比如鉴权,可结合 jwt 来实现。

以下代码 plugin-test/main.go 实现了 2 个 plugin:

package main

import (
	"github.com/micro/cli"
	"log"
	"net/http"

	"github.com/micro/micro/cmd"
	"github.com/micro/micro/plugin"
)

func main() {
	plugin.Register(plugin.NewPlugin(
		plugin.WithName("handle1"),
		plugin.WithInit(func(ctx *cli.Context) error {
			log.Println("init Handler1")
			return nil
		}),
		plugin.WithHandler(
			Handler1(),
		),
	))

	plugin.Register(plugin.NewPlugin(
		plugin.WithName("handle2"),
		plugin.WithInit(func(ctx *cli.Context) error {
			log.Println("init Handler2")
			return nil
		}),
		plugin.WithHandler(
			Handler2(),
		),
	))

	cmd.Init()
}

func Handler1() plugin.Handler {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			log.Println("call Handler1", r.URL.Path)
			h.ServeHTTP(w, r)
			return
		})
	}
}

func Handler2() plugin.Handler {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			log.Println("call Handler2", r.URL.Path)
			h.ServeHTTP(w, r)
			return
		})
	}
}

编译运行以上代码:

go build
./plugin-test api

我们通过浏览器输入 http://localhost:8080/,输出:

2022-01-16 02:16:19.737085 I | init Handler1
2022-01-16 02:16:19.737133 I | init Handler2
::1 - - [16/Jan/2022:02:28:49 +0800] "GET / HTTP/1.1" 200 21 "" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
2022-01-16 02:28:49.530683 I | call Handler1 /
2022-01-16 02:28:49.530845 I | call Handler2 /

我们可以看到两个插件handle1,handler2依次拦截 http 请求。

使用微服务架构后,后端的微服务有很多个,同一个微服务也会部署很多个实例,服务之间虽然可以通过服务发现,进而互相通信。那么如果我们想让一个 mobile app 或者 web app 调用我们的服务怎么办?这时 ...