這讓我在學習 Go 的最后一個月感到困惑:func Auth(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // hmmmm // ... next.ServeHTTP(w, r) }}在這里我們可以看到 Auth func 返回 type http.HandlerFunc。那個類型只是一個函數。那么當您調用時next.ServeHTTP,該方法是在何時/何處定義的?
1 回答

慕虎7371278
TA貢獻1802條經驗 獲得超4個贊
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
? ? f(w, r)
}
從字面上看,任何具有簽名的函數都func(ResponseWriter, *Request)可以轉換為 a HandlerFunc,這為它提供了方法ServeHTTP——然后簡單地調用該函數。
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報
0/150
提交
取消