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)
}
}
| 测试用例2:模拟一下,重定向到本地的某个接口下 |
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")
// 模拟重定向到login接口下
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")
}
// 测试用例2:模拟一下,重定向到本服务的某个API接口下
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
Login
Login In
打开浏览器,输入127.0.0.1:9090
会自动跳转到登录页面



