Reputation: 1407
The problem I'm having is pretty much the same as this post, but the answer there doesn't really give me a clear idea of how to solve it.
I want to send data to a new page after a user submits a form, so you naturally use ExecuteTemplate
from html/template
package.
This redirects a page to the new page with data, but the url stays the same.
This means that if you submitted a form on http://example.com/login
using ExecuteTemplate
, you go to a new page with data, but its url still shows http://example.com/login
.
I tried placing http.Redirect(w, r, "/newPage", http.StatusSeeOther)
just after the ExecuteTemplate
code, but the result was the same, which means that the page moved to the new page with data, but the url stayed http://example.com/login
instead of getting http://example.com/newPage
. Is there a solution to this?
I'm using Go version 1.13.3.
Upvotes: 0
Views: 2214
Reputation: 7903
You never have to display a template in a redirect response. It also doesn't make any sense.
There are 2 ways to achieve the effect you want.
This is your original workflow. You should think of this form page http://example.com/login
in 3 steps:
But how do you determine that you've reached (3)? One way is to append data to the URL on redirection. Let's say we read the GET parameter for a "step=2":
func loginPage(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("step") == "2" {
// show the form / page described in (3) above.
// ...
return
}
// suppose your form method is POST
if r.Method == "POST" {
if err := r.ParseForm(); err != nil {
// handle parse error
}
// handle form submission normally
// also somehow store the form submitted value for later use
// ...
// ...
// now redirect to the url, as described in (2)
http.Redirect(w, r, "/login?step=2")
return
}
// handle the normal form display as described in (1)
// do your ExecuteTemplate
}
Alternatively, you can also do this without any redirection. Just think of this in 2 steps:
func loginPage(w http.ResponseWriter, r *http.Request) {
// suppose your form method is POST
if r.Method == "POST" {
if err := r.ParseForm(); err != nil {
// handle parse error
}
// handle form submission normally
// also somehow store the form submitted value for later use
// ...
// ...
// handle the special form / page display as described in (2)
// do your ExecuteTemplate
// ...
// ...
return
}
// handle the normal form display as described in (1)
// do your ExecuteTemplate
}
Upvotes: 3