dourang6423 2017-03-21 01:41
浏览 39
已采纳

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

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 2017-03-21 02:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记