http.Redirect 是 Go 中实现重定向的标准方式,自动设置状态码和 Location 头;常用 302、301、303 状态码,调用后须 return 避免重复写响应。

在 Go 的 HTTP 服务中,使用 http.Redirect 是最直接、标准的方式实现重定向。它会自动设置状态码(如 302)和 Location 响应头,浏览器收到后立即跳转。
http.Redirect 是一个便捷函数,封装了状态码、响应头和空响应体的处理。它的签名是:
func Redirect(w ResponseWriter, r *Request, url string, code int)
其中:
- w 是响应写入器
- r 是当前请求(用于判断是否为 POST 等)
- url 是目标地址,支持相对路径(如 "/login")或绝对 URL(如 "https://example.com")
- code 是 HTTP 状态码,常用值有:
• http.StatusFound(302,默认推荐,适用于大多数跳转)
• http.StatusMovedPermanently(301,表示永久重定向,会影响 SEO 和浏览器缓存)
• http.StatusSeeOther(303,强制将后续请求转为 GET,适合表单提交后跳转)
以下是在实际 handler 中的典型用法:
http.Redirect(w, r, "/", http.StatusFound)
http.Redirect(w, r, "/login?next="+url.PathEscape(r.URL.Path), http.StatusFound)
http.Redirect(w, r, "/success", http.StatusSeeOther)
if r.URL.Scheme != "https" {<br> secureURL := "https://" + r.Host + r.URL.RequestURI()<br> http.Redirect(w, r, secureURL, http.StatusMovedPermanently)<br> return<br>}重定向不是“return”语句,而是向客户端发送响应。如果之后还继续写入响应体(比如调用 fmt.Fprint(w, "...")),会导致 “http: multiple response.WriteHeader calls” 错误。
立即学习“go语言免费学习笔记(深入)”;
http.Redirect 后务必 return,避免后续逻辑执行?msg=success)虽然可以直接写:
w.Header().Set("Location", "/new-path")<br>w.WriteHeader(http.StatusFound)http.Redirect。仅在需要精细控制(如自定义 header 或延迟写入)时才考虑手动操作。
基本上就这些。用好 http.Redirect 不复杂,关键是选对状态码、记得 return、别在重定向后继续写响应。
以上就是如何使用Golang处理HTTP重定向_使用http.Redirect控制页面跳转的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号