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" {
secureURL := "https://" + r.Host + r.URL.RequestURI()
http.Redirect(w, r, secureURL, http.StatusMovedPermanently)
return
}重定向不是“return
”语句,而是向客户端发送响应。如果之后还继续写入响应体(比如调用 fmt.Fprint(w, "...")),会导致 “http: multiple response.WriteHeader calls” 错误。
http.Redirect 后务必 return,避免后续逻辑执行?msg=success)虽然可以直接写:
w.Header().Set("Location", "/new-path")
w.WriteHeader(http.StatusFound)http.Redirect。仅在需要精细控制(如自定义 header 或延迟写入)时才考虑手动操作。
基本上就这些。用好 http.Redirect 不复杂,关键是选对状态码、记得 return、别在重定向后继续写响应。