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
)

yylany
11 声望0 粉丝