私が抱えている問題はこの投稿とほとんど同じですが、そこでの答えは、それを解決する方法についての明確な考えを実際には与えていません。
ユーザーがフォームを送信した後に新しいページにデータを送信したいのでExecuteTemplate
、html/template
パッケージから自然に使用します。
これにより、データのある新しいページにページがリダイレクトされますが、URLは変わりません。
つまり、をhttp://example.com/login
使用してフォームを送信した場合ExecuteTemplate
、データを含む新しいページに移動しますが、そのURLは引き続き表示されますhttp://example.com/login
。
コードのhttp.Redirect(w, r, "/newPage", http.StatusSeeOther)
直後に配置しようとしましたExecuteTemplate
が、結果は同じでした。つまり、ページはデータのある新しいページに移動しましたが、URL http://example.com/login
は取得されずにとどまっていましたhttp://example.com/newPage
。これに対する解決策はありますか?
Goバージョン1.13.3を使用しています。
リダイレクト応答でテンプレートを表示する必要はありません。また、意味がありません。
希望する効果を得るには2つの方法があります。
これが元のワークフローです。このフォームページhttp://example.com/login
は3つのステップで考える必要があります。
しかし、(3)に達したとどのように判断しますか?1つの方法は、リダイレクト時にデータをURLに追加することです。「step = 2」のGETパラメーターを読み取るとします。
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
}
または、リダイレクトせずにこれを行うこともできます。これを2つのステップで考えてください。
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
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加