如何在执行时使http.redirect()自动重定向?

huangapple go评论99阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年4月11日 01:14:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/71818884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定