golang web中间件

在web中添加自定义中间件

中间件,即处理函数,可以在路由函数处理前后实现一些自定义的逻辑。如中间件为[A,B,handler],则可以在运行路由函数之前运行函数A、B中的逻辑。他们的调用顺序可以在服务器中设置一个index表示正在运行中间件函数中的哪一个,然后设置一个next函数依次调用中间件的每个函数。

package main

import (
	"net/http"
	"fmt"
	"log"
)

type funcType func(s *myServer)
type myServer struct {
    content string
	midware []funcType
	handlers map[string]funcType
	index int
	w http.ResponseWriter
	r *http.Request
}
func (s *myServer)get(path string, f funcType) {
	s.handlers[path] = f
	s.midware = append(s.midware, f)
}
func (s *myServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.w = w
	s.r = r
	log.Println(r.URL)
	s.Next()
}

func (s *myServer) Next() {
	s.index++
	n := len(s.midware)
	for ; s.index < n; s.index++ {
		s.midware[s.index](s)
	}
}

func A() funcType {
	return func(s *myServer) {
		fmt.Println("A1")
		s.Next()
		fmt.Println("A2")
	}	
}

func B() funcType {
	return func(s *myServer) {
		fmt.Println("B1")
		s.Next()
		fmt.Println("B2")
	}	
}

func main() { 
	s := myServer{
		content: "Hello, World", 
		index: -1,
		handlers: make(map[string]funcType),
    }
	s.midware = append(s.midware, A())
	s.midware = append(s.midware, B())
	s.get("/hello", func(s *myServer){
		s.w.Header().Set("content-type", "text/plain")
		s.w.Write([]byte("hello"))
    })
	http.ListenAndServe(":8080", &s)   //创建服务且监听
}

运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值