Do you have to return after a http.Redirect if you want the code after to stop executing?

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

Do you have to return after a http.Redirect if you want the code after to stop executing?

问题

如果我在中间件中使用http.Redirect,那么在调用next.ServeHTTP(w, r)之前,我是否需要明确返回?

如果我有类似这样的代码,每次http.Redirect之后我是否需要明确返回,以便在重定向后停止执行代码?如果我不返回会发生什么?

// HTTPSNonWWWRedirect将HTTP请求重定向到HTTPS非www。
func HTTPSNonWWWRedirect(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.TLS == nil {
u := *r.URL
u.Scheme = "https"
if r.Host[:3] == "www" {
u.Host = r.Host[4:]
http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
return
}
http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
return
}
next.ServeHTTP(w, r)
})
}

英文:

If I use http.Redirect in a middleware, do I explicitly have to return after the http.Redirect before calling next.ServeHTTP(w, r)?

If I have something like this, do I have to return explicitly after every http.Redirect in order for the code to stop executing after the redirect? What happens if I don't return?

// HTTPSNonWWWRedirect redirects http requests to https non www.
func HTTPSNonWWWRedirect(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.TLS == nil {
			u := *r.URL
			u.Scheme = "https"
			if r.Host[:3] == "www" {
				u.Host = r.Host[4:]
				http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
				return
			}
			http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
			return
		}
		next.ServeHTTP(w, r)
	})
}

答案1

得分: 0

http.Redirect只是将用户重定向到不同的路由,它不会中断代码的执行。

你也可以使用else语句将最后的next.ServeHTTP(w, r)包裹起来,这样看起来更清晰。但是Go的习惯是使用return而不是else

英文:

http.Redirect just redirects the user to a different route. It does not break out from the code execution.

You could also use else statement to wrap around the last next.ServeHTTP(w, r) which makes it looks cleaner. But Go's idiom tends to use return instead of else.

huangapple
  • 本文由 发表于 2017年3月21日 09:41:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/42916952.html
匿名

发表评论

匿名网友

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

确定