看動畫跟著請求走一趟
瀏覽器GET /api/posts/42
http.Server:8080
中介層logging
ServeMux比對路由
handlergetPost
1func main() {2 mux := http.NewServeMux()3 mux.HandleFunc("GET /api/posts/{id}", getPost)4 5 handler := logging(mux)6 log.Fatal(http.ListenAndServe(":8080", handler))7}8 9func logging(next http.Handler) http.Handler {10 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {11 start := time.Now()12 next.ServeHTTP(w, r)13 log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))14 })15}16 17func getPost(w http.ResponseWriter, r *http.Request) {18 id := r.PathValue("id")19 post, ok := posts[id]20 if !ok {21 http.Error(w, "找不到文章", http.StatusNotFound)22 return23 }24 w.Header().Set("Content-Type", "application/json")25 json.NewEncoder(w).Encode(post)26}
回應(還在處理中)
第 1 / 8 站:使用者打開文章頁,瀏覽器送出 HTTP 請求:方法 GET、路徑 /api/posts/42。