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

yylany · · 563 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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
)

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:yylany

查看原文:重写micro网关,添加鉴权模块

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

563 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传