2023年即将到来,祝2023年更好
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
)
// MiddlewareFunc 中间件的函数
type MiddlewareFunc func(ctx context.Context, req interface{}) (resp interface{}, err error)
// Middleware 构建中间件函数使用
type Middleware func(MiddlewareFunc) MiddlewareFunc
// LogFile LogFile
type LogFile struct {
logName string
}
// buildMiddleWare 构建一个中间件函数
func buildMiddleWare(handle MiddlewareFunc) MiddlewareFunc {
var chain []Middleware
var LogFiler LogFile
chain = append(chain, frontHook)
chain = append(chain, newPrintLog(LogFiler))
middle := buildChain(chain)
return middle(handle)
}
// buildChain 构建链
/**
把中间件的数组构建成个链
最先执行的在最外层
next执行下一个 执行顺序和数组顺序相反
*/
func buildChain(chain []Middleware) Middleware {
return func(next MiddlewareFunc) MiddlewareFunc {
for i := len(chain) - 1; i >= 0; i-- {
next = chain[i](next)
}
return next
}
}
// frontHook 执行前置中间件
func frontHook(next MiddlewareFunc) MiddlewareFunc {
return func(ctx context.Context, req interface{}) (resp interface{}, err error) {
fmt.Println("执行前置中间件")
startTime := time.Now().UnixNano() / 1e6
resp, err = next(ctx, req) // 执行下一个
if err != nil {
log.Fatal(err)
return
}
endTime := time.Now().UnixNano() / 1e6
fmt.Println("函数执行时间为:", endTime-startTime)
return
}
}
// newPrintLog 打印日志中间件
func newPrintLog(LogFiler LogFile) Middleware {
return func(next MiddlewareFunc) MiddlewareFunc {
return func(ctx context.Context, req interface{}) (resp interface{}, err error) {
fmt.Println("打印日志中间件")
fmt.Println(LogFiler.logName, req)
resp, err = next(ctx, req)
return
}
}
}
// customHandler 自定义函数
func customHandler(ctx context.Context, req interface{}) (resp interface{}, err error) {
resp = req
fmt.Println("customHandle")
time.Sleep(time.Second)
return
}
// router router
func router(writer http.ResponseWriter, request *http.Request) {
MiddlewareFunction := buildMiddleWare(customHandler)
_, err := MiddlewareFunction(context.Background(), request)
if err != nil {
log.Fatal(err)
return
}
_, _ = writer.Write([]byte("<h1 style='color:red;'>2023水一贴</h1>"))
}
func main() {
//注册路由
http.HandleFunc("/", router)
//建立监听
err := http.ListenAndServe(fmt.Sprintf("127.0.0.1:%d", 8089), nil)
if err != nil {
log.Fatal(err)
return
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。