package main
import (
"fmt"
"log"
"net/http"
"time"
)
// 1. 实现一个 http server
// 2. 实现一个 handler:hello
// 3. 实现中间件的功能 1.记录请求URL和请求类型 2.记录请求的网络的地址 3.记录方法的执行时间
func tracing(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("tracing start 记录请求的网络地址:%s", r.RemoteAddr)
next.ServeHTTP(w, r)
log.Println("tracing end")
})
}
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("logging start 记录请求的网络地址:%s", r.RemoteAddr)
next.ServeHTTP(w, r)
log.Println("logging end")
})
}
func timeRecording(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("time Record start")
startTime := time.Now()
next.ServeHTTP(w, r)
lastTime := time.Since(startTime)
log.Printf("记录请求的耗时:%s", lastTime)
log.Println("time Record end")
})
}
func hello(w http.ResponseWriter, r *http.Request) {
//log.Printf("记录请求的网络地址:%s", r.RemoteAddr)
//log.Printf("记录请求的网络地址:%s", r.RemoteAddr)
//startTime := time.Now()
fmt.Fprintf(w, "hello")
//lastTime := time.Since(startTime)
//log.Printf("记录请求的耗时:%s", lastTime)
}
func main() {
http.Handle("/", tracing(logging(timeRecording(http.HandlerFunc(hello)))))
http.ListenAndServe("localhost:8080", nil)
}
// 执行结果
/private/var/folders/7w/0j7vff4j1kz5_g43cf_vqlg00000gp/T/GoLand/___go_build_designpattern_httpmiddleware
2023/02/27 14:35:59 tracing start 记录请求的网络地址:127.0.0.1:59347
2023/02/27 14:35:59 logging start 记录请求的网络地址:127.0.0.1:59347
2023/02/27 14:35:59 time Record start
2023/02/27 14:35:59 记录请求的耗时:32.877µs
2023/02/27 14:35:59 time Record end
2023/02/27 14:35:59 logging end
2023/02/27 14:35:59 tracing end
2023/02/27 14:35:59 tracing start 记录请求的网络地址:127.0.0.1:59347
2023/02/27 14:35:59 logging start 记录请求的网络地址:127.0.0.1:59347
2023/02/27 14:35:59 time Record start
2023/02/27 14:35:59 记录请求的耗时:2.526µs
2023/02/27 14:35:59 time Record end
2023/02/27 14:35:59 logging end
2023/02/27 14:35:59 tracing end