dongliao2241 2019-08-26 07:15
浏览 58
已采纳

Golang HTTP路由处理程序通用包装器实现

I'm trying to convert a route handler which returns response body and error instead of directly writing it to response writer. Then I want to send success/error response from the wrapper function instead.

It'll help me add tracing and metrics in a common place for all routes.

To achieve that, I tried this:

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 is an interface with signature:

Login(w http.ResponseWriter, r *http.Request) (*AuthenticationResponse, *types.HandlerErrorResponse)

Now, with this code the error comes in compilation:

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

But, to make generic Wrapper, I have to make my response body as interface.

Please let me know, how can I achieve it.

  • 写回答

1条回答 默认 最新

  • dongxiaoshe0737 2019-08-26 07:27
    关注

    To make it compile Login(w http.ResponseWriter, r *http.Request) (*AuthenticationResponse, *types.HandlerErrorResponse) needs to be Login(w http.ResponseWriter, r *http.Request) (interface{}, *types.HandlerErrorResponse)

    However I'd suggest you to define an inteface ( or use an existing one : io.Reader might be what you want )

    Define the methods you need to access from the response and then return that.

    type GenericBody interface{
        Bytes() []byte
    }
    

    Now as long as your return object implements this method, you can return it. However, the function signature will have to include this new type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目