Go 語言系列(十三):Web 框架 — Gin vs Echo

這是 Go 語言從零到 Web 應用系列的第十三篇,進入進階篇章。前面我們用標準庫 net/http 建構了完整的 Web 應用,現在來看看 Web 框架在標準庫之上提供了什麼價值。 為什麼需要 Web 框架? 標準庫 net/http 非常強大,但在建構大型應用時會遇到一些不便: // 標準庫:手動解析路由參數 mux := http.NewServeMux() mux.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) { // 需要手動從 URL 提取 ID id := strings.TrimPrefix(r.URL.Path, "/users/") if id == "" { http.Error(w, "missing id", http.StatusBadRequest) return } // 還需要手動判斷 HTTP method switch r.Method { case http.MethodGet: // 處理 GET case http.MethodPut: // 處理 PUT default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } }) Web 框架幫你解決的問題: 路由參數:/users/:id 自動解析 HTTP method 路由:GET /users/:id 和 PUT /users/:id 分開定義 請求綁定:JSON、Query、Form 自動綁定到 struct 參數驗證:struct tag 自動驗證 中間件:標準化的中間件鏈 錯誤處理:集中式錯誤處理 Go 生態中最熱門的兩個框架是 Gin 和 Echo,讓我們用同一個 API 來對比。 ...

2026年2月24日 · 4 min · 844 words · Jack