英文:
How to make http.redirect() to redirect automatically when executed
问题
使用这段代码,它会显示一个链接,点击后会重定向到/hello,如何在没有用户交互的情况下进行重定向?
package main
import (
"fmt"
"net/http"
)
func main() {
r := http.NewServeMux()
r.HandleFunc("/", index)
r.HandleFunc("/hello", hello)
http.ListenAndServe(":80", r)
}
func index(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/hello", http.StatusMovedPermanently)
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Println("hello")
}
在index
函数中,将http.Redirect
的第三个参数改为http.StatusMovedPermanently
,这样就可以在没有用户交互的情况下进行重定向。
英文:
With this code it show me a link to click for redirect to /hello, how do i make it redirect without user interaction?
package main
import (
"fmt"
"net/http"
)
func main() {
r := http.NewServeMux()
r.HandleFunc("/", index)
r.HandleFunc("/hello", hello)
http.ListenAndServe(":80", r)
}
func index(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/hello", 200)
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Println("hello")
}
答案1
得分: 1
如评论中已经回答的那样,在重定向的情况下,应返回标准的HTTP状态码[303]。因此,重定向行应为:
http.Redirect(w, r, "/hello", http.StatusSeeOther)
另外,请注意,使用http包中的http.XXX
比直接编写HTTP状态码更好。
英文:
As already answered in the comments, the standard HTTP code to be returned in case of a redirect is 303. So the redirect line should be:
http.Redirect(w, r, "/hello", http.StatusSeeOther)
Also note, using http package http.XXX
is preferred to writing HTTP codes directly
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论