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.
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.