登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-02 19:36:28 287浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《实现Golang通用的HTTP路由处理程序包装器》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我正在尝试转换一个返回响应正文和错​​误的路由处理程序,而不是直接将其写入响应编写器。 然后我想从包装函数发送成功/错误响应。

它将帮助我在所有路由的公共位置添加跟踪和指标。

为了实现这一点,我尝试了以下方法:

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

但是,为了制作通用包装器,我必须将响应正文设置为接口。

请告诉我,我怎样才能实现它。


解决方案


使其编译 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
}

现在只要你的返回对象实现了这个方法,就可以返回它。但是,函数签名必须包含这个新类型。

今天关于《实现Golang通用的HTTP路由处理程序包装器》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>