1package main
2
3import (
4 "log"
5 "net/http"
6 "time"
7)
8
9// 日志中间件
10func loggingMiddleware(next http.Handler) http.Handler {
11 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12 start := time.Now()
13
14 next.ServeHTTP(w, r)
15
16 log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
17 })
18}
19
20// 认证中间件
21func authMiddleware(next http.Handler) http.Handler {
22 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23 token := r.Header.Get("Authorization")
24 if token == "" {
25 http.Error(w, "Unauthorized", http.StatusUnauthorized)
26 return
27 }
28 next.ServeHTTP(w, r)
29 })
30}
31
32func main() {
33 mux := http.NewServeMux()
34 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
35 w.Write([]byte("Hello"))
36 })
37
38 // 链式中间件
39 handler := loggingMiddleware(authMiddleware(mux))
40 http.ListenAndServe(":8080", handler)
41}