1、Location
2、http.Redirect
代码
/index -> /login -> /home
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
func index(w http.ResponseWriter, r *http.Request) {
flag := true
if strings.Contains("/index", r.URL.Path){
flag = false
}
fmt.Println(flag)
w.Header().Set("Content-Type", "text/html")
w.Write(indexHTML)
}
var indexHTML = []byte(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button class="button">发送POST请求,登录</button>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(".button").click(
function (){
$.post("http://127.0.0.1:9090/login", {}, function (res){
console.log(res)
})
}
)
</script>
</body>
</html>
`)
func login(w http.ResponseWriter, r *http.Request) {
// way 1
fmt.Print(fmt.Sprintf("%v \n", r))
w.Header().Set("Cache-Control", "must-revalidate, no-store")
w.Header().Set("Content-Type", " text/html;charset=UTF-8")
w.Header().Set("Location", "http://127.0.0.1:9090/home")//跳转地址设置
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Method", "GET,OPTION,POST")
w.Header().Set("Access-Control-Allow-Headers", "http://127.0.0.1:9090/home")
w.WriteHeader(301)//关键在这里!
// way 2
// http.Redirect(w, r, "/home", 301)
}
func home(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write(homeHTML)
}
var homeHTML = []byte(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button class="button">登录成功!</button>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(".button").click(
function (){
$.post("http://127.0.0.1:9090/login", {}, function (res){
console.log("success !")
})
}
)
</script>
</body>
</html>
`)
func main() {
http.HandleFunc("/index", index)
http.HandleFunc("/login", login)
http.HandleFunc("/home", home)
err := http.ListenAndServe(":9090", nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}