使用http.Redirect可实现301、302等重定向,需传入响应写入器、请求对象、目标URL和状态码;支持永久重定向(301)、临时重定向(302)及条件跳转,如移动端适配或带参跳转,注意参数校验防止开放重定向。

在Golang中实现HTTP重定向非常简单,标准库net/http提供了直接的方法来完成301、302等常见的重定向操作。核心是使用http.Redirect函数,它能自动设置响应头中的Location字段并返回对应的状态码。
http.Redirect 是最常用的重定向方式,接受四个参数:响应写入器、请求对象、目标URL和状态码。
package main
<p>import (
"net/http"
)</p><p>func redirectHandler(w http.ResponseWriter, r *http.Request) {
// 重定向到 <a href="https://www.php.cn/link/42a61b38226d9f4a3bdeef465b616eb7">https://www.php.cn/link/42a61b38226d9f4a3bdeef465b616eb7</a> 302
http.Redirect(w, r, "<a href="https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635">https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635</a>", http.StatusFound)
}</p><p>func main() {
http.HandleFunc("/old-path", redirectHandler)
http.ListenAndServe(":8080", nil)
}
访问 /old-path 时,浏览器会跳转到指定的外部地址。状态码可选:
- http.StatusMovedPermanently (301):永久重定向
- http.StatusFound (302):临时重定向(最常用)
- 其他如 303、307 也可根据需要选择
当资源已永久迁移,建议使用 301 状态码,有助于SEO和缓存优化。
func permanentRedirect(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "/new-page", http.StatusMovedPermanently)
}
<p>http.HandleFunc("/old-page", permanentRedirect)
这样搜索引擎和客户端会更新对应的资源地址。
立即学习“go语言免费学习笔记(深入)”;
有时需要根据用户身份、设备类型或请求参数决定跳转目标。
func conditionalRedirect(w http.ResponseWriter, r *http.Request) {
    userAgent := r.Header.Get("User-Agent")
    if strings.Contains(userAgent, "Mobile") {
        http.Redirect(w, r, "/mobile-home", http.StatusFound)
    } else {
        http.Redirect(w, r, "/desktop-home", http.StatusFound)
    }
}
可以从原请求中提取查询参数,拼接到新URL中。
func redirectWithQuery(w http.ResponseWriter, r *http.Request) {
    query := r.URL.Query().Get("ref")
    target := fmt.Sprintf("https://newsite.com?ref=%s", query)
    http.Redirect(w, r, target, http.StatusFound)
}
注意对参数进行必要的校验和转义,避免开放重定向安全问题。
基本上就这些。Golang的http.Redirect足够应对大多数场景,关键是选对状态码并确保目标URL安全可靠。不复杂但容易忽略细节比如HTTPS强制跳转或循环重定向检测。
以上就是如何使用Golang实现HTTP重定向功能的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号