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 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动