英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论