Golang 请求重定向实现
在 Go 语言中,HTTP 请求重定向可以通过多种方式实现。以下是几种常见的重定向方法:
1. 使用标准库 net/http 实现重定向
临时重定向 (302)
package main
import (
"net/http"
)
func redirectHandler(w http.ResponseWriter, r *http.Request) {
// 临时重定向(302)
http.Redirect(w, r, "https://www.example.com", http.StatusFound)
}
func main() {
http.HandleFunc("/redirect", redirectHandler)
http.ListenAndServe(":8080", nil)
}
永久重定向 (301)
func permanentRedirectHandler(w http.ResponseWriter, r *http.Request) {
// 永久重定向(301)
http.Redirect(w, r, "https://www.example.com", http.StatusMovedPermanently)
}
2. Gin 框架中的重定向
如果你使用 Gin Web 框架:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/old-path", func(c *gin.Context) {
// 临时重定向(302)
c.Redirect(http.StatusFound, "/new-path")
// 或者永久重定向(301)
// c.Redirect(http.StatusMovedPermanently, "/new-path")
})
r.GET("/new-path", func(c *gin.Context) {
c.String(http.StatusOK, "Welcome to the new path!")
})
r.Run(":8080")
}
3. HTTP/HTTPS 强制跳转
func httpsRedirect(w http.ResponseWriter, r *http.Request) {
target := "https://" + r.Host + r.URL.Path
if len(r.URL.RawQuery) > 0 {
target += "?" + r.URL.RawQuery
}
log.Printf("redirect to: %s", target)
// Permanent Redirect (308 for POST/PUT/DELETE requests to preserve method)
if r.Method == http.MethodPost ||
r.Method == http.MethodPut ||
r.Method == http.MethodDelete {
w.Header().Set("Connection", "close")
url := fmt.Sprintf("https://%s%s", r.Host, r.RequestURI)
http.Redirect(w, r, url, http.StatusPermanentRedirect)
} else {
// For GET/HEAD requests use standard redirect (301 or 302)
http.Redirect(w, r, target, http.StatusMovedPermanently)
}
}
func main() {
go func() {
// HTTP server that redirects to HTTPS
if err := http.ListenAndServe(":80",
http.HandlerFunc(httpsRedirect)); err != nil {
log.Fatalf("ListenAndServe error: %v", err)
}
}()
// Your HTTPS server setup here...
}
4. URL路由参数保留的重定向
func redirectWithParams(c *gin.Context) {
name := c.Param("name")
id := c.Query("id")
newPath := fmt.Sprintf("/new-location/%s?id=%s&from=redirect", name, id)
c.Redirect(http.StatusFound, newPath)
}
HTTP状态码说明
- 301 Moved Permanently - SEO友好,浏览器会缓存此结果,后续直接访问新地址
- 302 Found - SEO不友好,每次都会先访问旧地址再跳转(临时跳转)
- 307 Temporary Redirect - HTTP/1.1新增,确保方法和body不变的重定向(POST等非GET请求)
- 308 Permanent Redirect - HTTP/1.1新增,类似307但是是永久的
根据你的具体需求选择合适的重定向类型!
内容由零声教学AI助手提供,问题来源于学员提问




