为了账号安全,请及时绑定邮箱和手机立即绑定

如何在单个入口点中自定义来自两个处理程序的响应数据?

如何在单个入口点中自定义来自两个处理程序的响应数据?

Go
蛊毒传说 2023-02-06 19:34:45
我在我的应用程序中使用 echo 框架,我遇到了在单个入口点上构造来自两个处理程序的响应的问题。有示例代码type RespObject struct {    Message string `json:"message"`}func main() {    e := echo.New()    e.GET("/hello", handler, middle)    e.Logger.Fatal(e.Start(":3000"))}func handler(c echo.Context) error {    return c.JSON(http.StatusOK, RespObject{        Message: "Hello",    })}func middle(next echo.HandlerFunc) echo.HandlerFunc {    return func(c echo.Context) error {        c.JSON(http.StatusOK, RespObject{            Message: "World",        })        return next(c)    }}请求后我得到curl localhost:3000/hello{"message":"World"}{"message":"Hello"}我的目标是做出回应{"message":"Hello World"}echo.Context 具有带有实现 ResponseWriter 的结构 Response但似乎 ResponseWriter 是 WriteOnly 合同。有没有办法在 ResponseWriter 中擦除和重建数据?据我所知有两个问题通过“中间”处理程序后从 ResponseWriter 读取数据。擦除 ResponseWriter 中的数据并在“处理程序”处理程序中写入新数据在实际问题中,结构的名称冲突是没有必要的。它在两个不同的 SCIM API 中请求并做出组合响应。
查看完整描述

1 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

这可以通过创建一个自定义函数来实现,该函数将响应对象和代码添加到上下文并在处理程序中调用它;在中间件中,您从上下文中获取此对象,修改响应并调用实际的 c.JSON,它将修改后的响应写入线路。


const (

    echoCtxRespKey = "echo_ctx_resp_key"

)


type RespObject struct {

    Message string `json:"message"`

}


type Response struct {

    Data interface{}

    Code int

}


func main() {

    e := echo.New()

    e.GET("/hello", handler, middle)


    e.Logger.Fatal(e.Start(":3000"))

}


func handler(c echo.Context) error {

    resp := RespObject{

        Message: "Hello",

    }

    addResponseToContext(c, Response{

        Data: resp,

        Code: http.StatusOK,

    })

    

    return nil 

}


func middle(next echo.HandlerFunc) echo.HandlerFunc {

    return func(c echo.Context) error {

        next(c)

        

        resp := getResponseFromContext(c)

        

        // modify resp

        

        return c.JSON(resp.Code, resp.Data)

    }

}


func addResponseToContext(c echo.Context, response Response) {

    c.Set(echoCtxRespKey, response)

}


func getResponseFromContext(c echo.Context) Response {

    return c.Get(echoCtxRespKey).(Response)

}


查看完整回答
反对 回复 2023-02-06
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信