Golang web filter 轻量级实现

前言

golang web 通过http handle模块进行restful接口与请求处理绑定;既然用了restful每个公司或项目都会制定自己的设计原则和约束条件。在日常开发中通常会根据uri匹配规则在请求进入controller之前进行一些特殊处理(权限、功能验证...);在Java web编程中 servlet filter帮助我们实现了这样的功能,golang web通过扩展http handle即可实现

案例:

/safe /safe/user

假定: 以/safe开头的请求对客户端请求参数进行解密 以/safe/user开头的请求不仅要对客户端请求参数进行解密还要验证当前请求用户是否在线

实现思路:

定义FilterHandle、WebHandle类型

type FilterHandle func(rw http.ResponseWriter,r *http.Request) error

type WebHandle func(rw http.ResponseWriter,r *http.Request) error
复制代码

FilterHandle 拦截器处理函数 WebHandle 客户端请求处理函数

http handle模块与拦截器处理函数绑定 在拦截器处理函数中通过闭包回调WebHandle

注册拦截器处理函数 func Register(uriRule string,fh FilterHandle)

uri 路径匹配规则

★★★★★ 拦截器注册在http server 启动前

web filter代码示例:

/**
 * Created with IntelliJ IDEA.
 * Description: 
 * User: yangzhao
 * Date: 2018-08-02
 * Time: 11:01
 */
package web_filter

import (
	"net/http"
	"strings"
)

type FilterHandle func(rw http.ResponseWriter,r *http.Request) error

//拦截uri映射处理
var filterMapping = make(map[string]FilterHandle,0)
//保证有序uri
var uriArray = make([]string,0)

/**
	uriRule 路径匹配规则
	fh 拦截器处理函数
 */
func Register(uriRule string,fh FilterHandle)  {
	uriRule = uriRule[:len(uriRule)-2]
	filterMapping[uriRule]=fh
	uriArray = append(uriArray,uriRule)
}

type WebHandle func(rw http.ResponseWriter,r *http.Request) error

func Handle(webHandle WebHandle) func(rw http.ResponseWriter,r *http.Request) {

	return func(rw http.ResponseWriter,r *http.Request){
		var uri=r.RequestURI
		uri+="/"
		for _,v:=range uriArray{
			if strings.Contains(uri,v) {
				e := filterMapping[v](rw, r)
				if e != nil {
					rw.Write([]byte(e.Error()))
					return
				}

			}
		}
		err := webHandle(rw, r)
		if err != nil {
			rw.Write([]byte(err.Error()))
		}
	}
}

复制代码

测试demo

/**
 * Created with IntelliJ IDEA.
 * Description: 
 * User: yangzhao
 * Date: 2018-08-01
 * Time: 16:16
 */
package test

import (
	"net/http"
	"log"
	"errors"
	"testing"
	"common-go/web/filter"
	"fmt"
)

type HttpServer struct {
	
	http.Server
	
}

func (server *HttpServer) StartServer()  {
	log.Println("web server start "+server.Addr)
	err := server.ListenAndServe()
	if err != nil {
		log.Panic(err)
	}
}

func (server *HttpServer)ServeHTTP(wr http.ResponseWriter, r *http.Request)()  {
	fmt.Println("测试")
}

func TestWebFilter(t *testing.T) {
	web_filter.Register("/safe/**", func(rw http.ResponseWriter, r *http.Request)error {
		return errors.New("解密失败")
		//return nil
	})
	web_filter.Register("/safe/user/**", func(rw http.ResponseWriter, r *http.Request)error {
		return errors.New("请登录")
		//return nil
	})
	http.HandleFunc("/safe", web_filter.Handle(func(wr http.ResponseWriter,req *http.Request) error{
		wr.Write([]byte(req.RequestURI))
		return nil
	}))

	http.HandleFunc("/safe/user/test", web_filter.Handle(func(wr http.ResponseWriter,req *http.Request) error{
		wr.Write([]byte(req.RequestURI))
		return nil
	}))

	http.HandleFunc("/safe/user", web_filter.Handle(func(wr http.ResponseWriter,req *http.Request) error{
		wr.Write([]byte(req.RequestURI))
		return nil
	}))

	server := &HttpServer{}
	server.Addr=":8080"
	server.StartServer()
}
复制代码

以上属于原创文章,转载请注明作者@怪咖

QQ:208275451

你可能感兴趣的:(Golang web filter 轻量级实现)