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.

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

报告相同问题?