使用http.Redirect可实现301/302重定向,支持静态路径、动态参数及HTTPS跳转,需校验目标URL防止开放重定向。

在Golang中实现HTTP重定向非常简单,标准库net/http提供了直接支持。通过合理使用http.Redirect函数,你可以轻松完成301永久重定向或302临时重定向,适用于跳转登录页、旧链接迁移等场景。
Go的http.Redirect函数是实现重定向的核心工具。它接受响应写入器、请求对象和目标URL,自动设置状态码和Location头。
以下是一个基础示例,将所有请求从/old重定向到/new:
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/old", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/new", http.StatusFound) // 302
})
http.HandleFunc("/new", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome to the new page!"))
})
http.ListenAndServe(":8080", nil)
}
StatusFound (302)表示临时重定向,浏览器会缓存当前地址;若要永久重定向,可使用http.StatusMovedPermanently (301)。
立即学习“go语言免费学习笔记(深入)”;
实际项目中,重定向目标可能依赖用户输入或路径参数。Go可以通过解析URL或表单数据动态生成跳转地址。
例如,根据查询参数跳转不同页面:
http.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
target := r.URL.Query().Get("to")
if target == "" {
target = "/" // 默认跳转首页
}
http.Redirect(w, r, target, http.StatusSeeOther) // 303
})
访问/redirect?to=/profile即可跳转到个人页。注意校验目标URL防止开放重定向漏洞,建议对目标域名做白名单控制。
在生产环境中,常需将HTTP请求重定向到HTTPS。可通过启动两个服务监听不同端口来实现。
示例:HTTP服务器将所有请求301重定向到HTTPS版本:
// HTTP server (port 80)
go http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host := r.Host // 如 localhost:8080
http.Redirect(w, r, "https://"+host+r.URL.Path, http.StatusMovedPermanently)
}))
// HTTPS server (port 443)
http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
这种做法常见于Web安全加固,确保用户始终通过加密连接访问。
当迁移网站结构时,旧的静态资源路径需要重定向到新位置。可以结合http.FileServer和自定义处理器实现。
例如,将/images/old-logo.png重定向到新CDN地址:
http.HandleFunc("/images/old-logo.png", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://cdn.example.com/new-logo.png", http.StatusMovedPermanently)
})
也可批量处理前缀路径,比如把/blog-old/下的所有请求转发到/blog/。
以上就是如何在Golang中实现简单的HTTP重定向_Golang HTTP重定向项目实战汇总的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号