1. 首页
  2. IT资讯

重写micro网关,添加鉴权模块

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
)

本文来自投稿,不代表程序员编程网立场,如若转载,请注明出处:http://www.cxybcw.com/203201.html

联系我们

13687733322

在线咨询:点击这里给我发消息

邮件:1877088071@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

QR code