在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) //创建服务且监听
}
运行结果