micro 网关鉴权
这个鉴权无非就是通过中间件来管制拜访,须要重写 micro 代码
咱们只须要编写一个 plugin 函数,并注册到 micro 外面即可实现申请中间件的性能
代码如下
package main
import (
"fmt"
"github.com/micro/cli"
"github.com/micro/micro/cmd"
"github.com/micro/micro/plugin"
"net/http"
)
func JWTAuthWrapper() plugin.Handler {return func(h http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Println("解决 http")
h.ServeHTTP(w, r)
})
}
}
func jwtPlugin() plugin.Plugin {
//jwt 鉴权
return plugin.NewPlugin(plugin.WithName("auth"),
plugin.WithHandler(JWTAuthWrapper()),
// 参数
plugin.WithFlag(cli.StringFlag{
Name: "consul_address",
Usage: "consul address for K/V",
EnvVar: "CONSUL_ADDRESS",
Value: "127.0.0.1:8500",
}),
plugin.WithInit(func(ctx *cli.Context) error {fmt.Println("初始化")
return nil
}))
}
func main() {_ = plugin.Register(jwtPlugin())
cmd.Init()}
go.mod 文件
module demo
go 1.13
require (
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5
github.com/go-sql-driver/mysql v1.5.0
github.com/micro/cli v0.2.0
github.com/micro/go-plugins v1.5.1
github.com/micro/micro v1.18.0
)