1??go grpc-go 相关技术专栏 总入口
2??Protobuf介绍与实战 图文专栏 文章目录
本篇文章仅作为笔记使用。
测试重定向
在http.ResponseWriter类型中设置重定向
测试用例1:模拟一下,重定向到某个url地址,如百度 |
package header
import (
"fmt"
"log"
"net/http"
"testing"
)
func login(w http.ResponseWriter, r *http.Request) {
fmt.Print(fmt.Sprintf("%v+", 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://www.baidu.com/")
w.WriteHeader(http.StatusFound)
}
func TestResponseHeader(t *testing.T) {
http.HandleFunc("/", login)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
test.go
import (
"fmt"
"log"
"net/http"
"os"
"testing"
)
func authorizeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Print(fmt.Sprintf("%v+", r))
w.Header().Set("Cache-Control", "must-revalidate, no-store")
w.Header().Set("Content-Type", " text/html;charset=UTF-8")
w.Header().Set("Location", "/login")
w.WriteHeader(http.StatusFound)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("\n-----打开---Login.html---")
outputHTML(w, r, "static/login.html")
}
func TestResponseHeader2(t *testing.T) {
http.HandleFunc("/", authorizeHandler)
http.HandleFunc("/login", loginHandler)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func outputHTML(w http.ResponseWriter, req *http.Request, filename string) {
file, err := os.Open(filename)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer file.Close()
fi, _ := file.Stat()
http.ServeContent(w, req, file.Name(), fi.ModTime(), file)
}
在test.go的同级目录下, 创建一个static目录 在static目录下创建静态文件,如 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Login In</h1>
<form action="/login" method="POST">
<div class="form-group">
<label for="username">User Name</label>
<input type="text" class="form-control" name="username" required placeholder="Please enter your user name">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Please enter your password">
</div>
<button type="submit" class="btn btn-success">Login</button>
</form>
</div>
</body>
</html>
打开浏览器,输入127.0.0.1:9090 会自动跳转到登录页面
|