我正在嘗試轉換返回響應正文和錯誤的路由處理程序,而不是直接將其寫入響應編寫器。然后我想從包裝函數發送成功/錯誤響應。它將幫助我在所有路由的公共位置添加跟蹤和指標。為了實現這一目標,我嘗試了以下方法:router.HandleFunc(app, "/login", WrapHandler(Login)).Methods("POST")func WrapHandler(handler func(http.ResponseWriter, *http.Request) (interface{}, *types.HandlerErrorResponse)) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { response, errResponse := handler(w, r) sendResponse(r.Context(), w, response, errResponse) }}登錄是一個帶簽名的接口:Login(w http.ResponseWriter, r *http.Request) (*AuthenticationResponse, *types.HandlerErrorResponse)現在,使用這段代碼,錯誤出現在編譯中:cannot use Login (type func(http.ResponseWriter, *http.Request) (*AuthenticationResponse, *types.HandlerErrorResponse)) as type func(http.ResponseWriter, *http.Request) (interface {}, *types.HandlerErrorResponse) in argument to WrapHandlerNew但是,為了制作通用包裝器,我必須將響應主體作為接口。請讓我知道,我怎樣才能實現它。
1 回答
牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
要使其編譯 Login(w http.ResponseWriter, r *http.Request) (*AuthenticationResponse, *types.HandlerErrorResponse)需要Login(w http.ResponseWriter, r *http.Request) (interface{}, *types.HandlerErrorResponse)
不過,我建議您定義一個接口(或使用現有的接口:io.Reader可能就是您想要的)
定義您需要從響應中訪問的方法,然后返回該方法。
type GenericBody interface{
Bytes() []byte
}
現在只要你的返回對象實現了這個方法,就可以返回它。但是,函數簽名必須包含這個新類型。
- 1 回答
- 0 關注
- 158 瀏覽
添加回答
舉報
0/150
提交
取消
