Golang中http.Redirect不跳转的问题如何解决
Golang中http.Redirect不跳转的问题如何解决 大家好,我一直在努力弄清楚为什么下面的代码似乎无法工作:
func FormHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
uname := r.FormValue("uname")
pwd := r.FormValue("pwd")
if uname == "admin" && pwd == "root" {
http.Redirect(w, r, "https://www.google.com", http.StatusFound)
} else {
http.Redirect(w, r, "https://wikipedia.com", http.StatusFound)
}
case "GET":
p := ("./website/portal.html")
http.ServeFile(w, r, p)
}
}
(链接到维基百科和谷歌仅用于测试目的)
以下是相关的 HTML 表单:
<form method="post">
<label for="uname">Username</label><br>
<input type="text" id="uname" name="uname"><br>
<label for="pwd">Password</label><br>
<input type="password" id="pwd" name="pwd">
<input type="submit" value="Log in">
</form>
GET 方法工作正常,我想不出问题可能出在哪里,任何帮助都将不胜感激。感谢阅读。
更多关于Golang中http.Redirect不跳转的问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html
7 回复
非常感谢,这确实很有帮助! 😊
更多关于Golang中http.Redirect不跳转的问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
我认为你的表单缺少一个动作属性:
<form method="post" action="/path/to/action">
你好,感谢你的快速回复。我添加了 ParseForm 这行代码,但它仍然不起作用。非常感谢任何其他的建议。
我认为你在读取表单值之前漏掉了 ParseForm:
r.ParseForm()
uname := r.FormValue("uname")
pwd := r.FormValue("pwd")
啊,现在我明白了。我之前不确定应该将表单数据发送到哪里,因为根据内容的不同,它会重定向到两个网站中的一个。
问题出在http.Redirect调用后没有正确返回。当调用http.Redirect设置重定向响应后,需要立即返回,否则后续代码会继续执行,可能导致响应被覆盖。
以下是修正后的代码:
func FormHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
uname := r.FormValue("uname")
pwd := r.FormValue("pwd")
if uname == "admin" && pwd == "root" {
http.Redirect(w, r, "https://www.google.com", http.StatusFound)
return // 关键:重定向后立即返回
} else {
http.Redirect(w, r, "https://wikipedia.com", http.StatusFound)
return // 关键:重定向后立即返回
}
case "GET":
p := ("./website/portal.html")
http.ServeFile(w, r, p)
}
}
另一个可能的问题是表单提交到相对路径。确保表单的action属性正确设置:
<form method="post" action="/your-handler-path">
<label for="uname">Username</label><br>
<input type="text" id="uname" name="uname"><br>
<label for="pwd">Password</label><br>
<input type="password" id="pwd" name="pwd">
<input type="submit" value="Log in">
</form>
如果问题仍然存在,可以添加错误处理和日志来调试:
func FormHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
uname := r.FormValue("uname")
pwd := r.FormValue("pwd")
fmt.Printf("Received POST: uname=%s, pwd=%s\n", uname, pwd)
if uname == "admin" && pwd == "root" {
fmt.Println("Redirecting to Google")
http.Redirect(w, r, "https://www.google.com", http.StatusFound)
return
} else {
fmt.Println("Redirecting to Wikipedia")
http.Redirect(w, r, "https://wikipedia.com", http.StatusFound)
return
}
case "GET":
p := ("./website/portal.html")
fmt.Println("Serving file:", p)
http.ServeFile(w, r, p)
}
}
确保在导入部分添加fmt包来使用打印语句进行调试。


