HTTP
Go 標準庫 net/http 套件參考。
HTTP Server - Before 1.22 vs After 1.22
HTTP Functions 比較
| Feature | http.HandlerFunc | http.HandleFunc | http.Handler | http.Handle |
|---|---|---|---|---|
| Type | Function type | Function | Interface | Function |
| Main use | Convert functions to Handler | Register handler functions | Define handler interface | Register handlers |
| Implementation | Implements ServeHTTP method | Calls http.Handle | Implements ServeHTTP method | Direct use |
| Parameters | func(ResponseWriter, *Request) | pattern, func(ResponseWriter, *Request) | - | pattern, Handler |
| Common use cases | Middleware, type conversion | Quick registration of simple routes | Custom complex handlers | Register any Handler implementation |
| Flexibility | High | Medium | High | High |
| Direct API endpoint registration | No | Yes | No | Yes |
| Customizable logic | Yes | Yes | Yes | Yes |
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 的實現