2 回答

TA貢獻1807條經驗 獲得超9個贊
您需要使用 .將mw.Middleware()語句的第二個參數包裝到類型中。http.Handlerhttp.HandlerFunc()
func (h Handler) makeGetMany(v Injection) http.HandlerFunc {
return mw.Middleware(
mw.Allow("admin"),
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("now we are sending response.");
json.NewEncoder(w).Encode(v.Share)
}),
)
}

TA貢獻1111條經驗 獲得超0個贊
在 http 包中,?ListenAndServe具有以下簽名
func?ListenAndServe(addr?string,?handler?Handler)?error
其中Handler
(ie,?http.Handler
) 是一個接口
type?Handler?interface?{ ????ServeHTTP(ResponseWriter,?*Request) }
對于一個 Web 應用程序,只有一個ListenAndServe
調用,因此只有一個handler
,它需要處理所有訪問點,例如/url1
,/url2
等。如果我們從頭開始編寫handler
,實現可能是struct
一個圍繞數據庫句柄的自定義。它的ServeHTTP
方法是檢查訪問點,然后把相應的內容寫入到ResponseWriter
,比較繁瑣和雜亂。
這就是ServeMux的動機,它router
在您的代碼中。它有一個ServeHTTP方法,因此它滿足http.Handler
接口并可用于ListenAndServe
.?此外,它還有HandleFunc
處理個別接入點的方法
func?(mux?*ServeMux)?HandleFunc(pattern?string, ????????????????????????????????handler?func(ResponseWriter,?*Request))
注意這里handler
不是 a?http.Handler
,即它沒有ServeHTTP
方法。它不必這樣做,因為它mux
已經擁有ServeHTTP
并且它的ServeHTTP
方法可以將各個訪問點請求分派給相應的處理程序。
請注意,它還有一個Handle
方法,該方法需要參數滿足http.Handler
接口。與方法相比,使用起來稍微不方便HandleFunc
。
func?(mux?*ServeMux)?Handle(pattern?string,?handler?Handler)
現在回到你的問題,因為你打電話router.HandleFunc
,它的輸入不一定是http.Handler
。因此,另一種解決方案是用作func(ResponseWriter, *Request)
中間件和makeGetMany
方法的返回類型。(中間件中的類型斷言也需要更新,可能還需要更新更多代碼)
@xpare 的解決方案是進行類型轉換,以便所有函數簽名匹配,即轉換func(ResponseWriter, *Request)
為http.HandlerFunc
.?看看它是如何工作的也很有趣。
// 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)
}
你可以看到它基本上定義了一個ServeHTTP調用自身的方法。
- 2 回答
- 0 關注
- 156 瀏覽
添加回答
舉報