简体   繁体   English

httprouter 转发到带有参数和 url 更新的另一个处理程序

[英]httprouter forward to another handler with parameters & url update

I'm thinking about the following scenario:我正在考虑以下场景:

Suppose I want have handler X in which I have made some calculations but now want to forward to another handler Y before returning the request.假设我想要处理程序 X,我在其中进行了一些计算,但现在想在返回请求之前转发到另一个处理程序 Y。

It would be something like会是这样的

func X(w http.ResponseWriter, r *http.Request, params httprouter.Params){
    //calculations
    if condition{
        var fp httprouter.Params
        fp = append(fp, httprouter.Param{Key: "KEY", Value: "VALUE"})
        w.WriteHeader(301)
        Y(w, r, fp)
        return
    }
}

The problem I have is that while the page loads and it has a 301 header the redirect is not registered.我遇到的问题是,当页面加载并且它有 301 header 时,重定向未注册。 It's like a 200 page with a 301.这就像一个 301 的 200 页。

I know there's http.Redirect, but it doesn't forward the parameters that could be helpful.我知道有 http.Redirect,但它不会转发可能有用的参数。 Is there an easy solution to this?有一个简单的解决方案吗?

"If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data." “如果还没有调用 WriteHeader,Write 会在写入数据之前调用 WriteHeader(http.StatusOK)。” (From http.Server documentation ) (来自http.Server 文档

Make sure you don't write any bytes to the ResponseWriter if you think you will redirect.如果您认为您将重定向,请确保您不向 ResponseWriter 写入任何字节。 You can user a buffer or something instead of writing directly to the w您可以使用缓冲区或其他东西,而不是直接写入w

As far as getting your first function's parameters into your second function... You could use cookies, or easier.至于将第一个函数的参数放入第二个 function... 您可以使用 cookies,或更简单。 The redirect path could include the parameters.重定向路径可以包含参数。 Either as path or GET variables.作为路径或 GET 变量。 Here's an example with path using that httprouter package you are already using.这是一个使用您已经在使用的 httprouter package 的路径示例。

In X(),在 X() 中,

    if weAreRedirecting {
        http.Redirect(w, r, "/y/"+params.ByName("key"), http.StatusFound)
        return
    }

And in your router, router.GET("/y/:key", Y)在你的路由器中, router.GET("/y/:key", Y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM