0

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.

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. It's like a 200 page with a 301.

I know there's http.Redirect, but it doesn't forward the parameters that could be helpful. Is there an easy solution to this?

Jiulin Teng
  • 299
  • 3
  • 8
  • Do you want to http-redirect to a different handler, or simply call the other handler? If you want to simply call it, do not write output (no WriteHeader), and just call the other handler. – Burak Serdar Jan 03 '21 at 22:08
  • To redirect, because in this case it would be a 301. I didn't really need to use this type of redirect, but I thought there may be cases where it's needed. – Jiulin Teng Jan 03 '21 at 23:56
  • If you need to redirect, you have to use http.Redirect in the first handler, and let the client call the second handler once it receives the redirect. – Burak Serdar Jan 04 '21 at 00:31

1 Answers1

0

"If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data." (From http.Server documentation)

Make sure you don't write any bytes to the ResponseWriter if you think you will redirect. You can user a buffer or something instead of writing directly to the w

As far as getting your first function's parameters into your second function... You could use cookies, or easier. The redirect path could include the parameters. Either as path or GET variables. Here's an example with path using that httprouter package you are already using.

In X(),

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

And in your router, router.GET("/y/:key", Y)

aerth
  • 468
  • 4
  • 8
  • No, I wrote 301 because it needed to be 301, and then 200. After some thought, I guess it's not possible. Perhaps it's also not an important feature. – Jiulin Teng Jan 04 '21 at 09:42
  • And if it needs to be passed as parameter, sometimes information would be leaked. – Jiulin Teng Jan 04 '21 at 09:43