dourang6423
dourang6423
2017-03-21 01:41

如果要停止执行代码,是否必须在http.Redirect之后返回?

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

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条回答

  • doudi1979 doudi1979 4年前

    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.

    点赞 评论 复制链接分享