HTTP

Go 標準庫 net/http 套件參考。

HTTP Server - Before 1.22 vs After 1.22

HTTP Functions 比較

Featurehttp.HandlerFunchttp.HandleFunchttp.Handlerhttp.Handle
TypeFunction typeFunctionInterfaceFunction
Main useConvert functions to HandlerRegister handler functionsDefine handler interfaceRegister handlers
ImplementationImplements ServeHTTP methodCalls http.HandleImplements ServeHTTP methodDirect use
Parametersfunc(ResponseWriter, *Request)pattern, func(ResponseWriter, *Request)-pattern, Handler
Common use casesMiddleware, type conversionQuick registration of simple routesCustom complex handlersRegister any Handler implementation
FlexibilityHighMediumHighHigh
Direct API endpoint registrationNoYesNoYes
Customizable logicYesYesYesYes

Use Cases

  • Links

  • 需要 Global Middleware 時,使用 Handler

  • 需要 Router Level - Middleware 時,使用 HandlerFunc

  • 簡單的路由處理,直接使用 HandleFunc

Handler 介面

使用 struct 實現 Handler 介面:

type UserHandler struct {
    db        *sql.DB       // 資料庫連接
    cache     *redis.Client // Redis 客戶端
    apiKey    string        // API 金鑰
    userCount int           // 用戶計數器
}

適用場景

  • 需要保持配置(如資料庫連接、快取客戶端)
  • 需要共享狀態(如計數器、緩存)
  • 需要依賴注入
  • 需要維護複雜的內部狀態

Middleware Chain

  • 日誌記錄中間件
  • 認證檢查中間件
  • 可以輕易地添加新的中間件

API Router Group

  • 統一的路徑前綴
  • 統一的中間件應用
  • 簡化的路由註冊

HandlerFunc 類型

是一個函數類型,自動實現了 Handler 介面。

http.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "OK")
})

適用場景

  • 簡單的請求處理
  • 無狀態的操作
  • 單一職責的端點
  • 不需要共享資源

HandleFunc 方法

  • 將普通函數轉換為 Handler
  • 實現路由層級的中間件
  • 簡化 Handler 的實現