栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go http header 重定向测试用例

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go http header 重定向测试用例

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
会自动跳转到登录页面

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/904973.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号