使用go语言写一个执行时间中间件,不太明白中间件timeHandler部分的执行过程.
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is index!")
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!")
}
//这个不太懂.过程有点难理解
func timeHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
log.Printf("Strated %s %s ", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
log.Printf("Completed %s in %v", r.URL.Path, time.Since(start))
})
}
func asd(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "yaochizaocan")
}
func main() {
mux := http.NewServeMux() //创建一个路由转发器.
mux.Handle("/asd", timeHandler(http.HandlerFunc(asd))) //将写好的asd函数到写好的timehandler中间件进行注册.
mux.Handle("/hello", timeHandler(http.HandlerFunc(hello)))
mux.Handle("/", timeHandler(http.HandlerFunc(index)))
http.ListenAndServe(":8080", mux)
}