温馨提示×

golang重定向方法怎么调用

小亿
142
2023-07-04 21:05:21
栏目: 编程语言

在Golang中,可以使用http.Redirect函数来实现重定向。

package main
import (
"net/http"
)
func redirectHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://www.example.com", http.StatusFound)
}
func main() {
http.HandleFunc("/redirect", redirectHandler)
http.ListenAndServe(":8080", nil)
}

在上面的示例中,redirectHandler函数会被注册为处理/redirect路径的请求。当收到该请求时,http.Redirect函数会将响应重定向到http://www.example.com网站,并返回状态码http.StatusFound

你可以根据自己的需求修改重定向的目标URL和状态码。

0