亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang HTTP 路由處理程序通用包裝器實現

Golang HTTP 路由處理程序通用包裝器實現

Go
白衣染霜花 2023-07-17 14:47:00
我正在嘗試轉換返回響應正文和錯誤的路由處理程序,而不是直接將其寫入響應編寫器。然后我想從包裝函數發送成功/錯誤響應。它將幫助我在所有路由的公共位置添加跟蹤和指標。為了實現這一目標,我嘗試了以下方法: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

}

現在只要你的返回對象實現了這個方法,就可以返回它。但是,函數簽名必須包含這個新類型。


查看完整回答
反對 回復 2023-07-17
  • 1 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號