unit-testing - 具有自定义 ServeHTTP 实现的 http 处理程序的 golang 单元测试
问题描述
我正在尝试为我的 http 文件服务器编写单元测试。我已经实现了 ServeHTTP 函数,以便它将 URL 中的“//”替换为“/”:
type slashFix struct {
mux http.Handler
}
func (h *slashFix) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.Replace(r.URL.Path, "//", "/", -1)
h.mux.ServeHTTP(w, r)
}
最低限度的代码如下所示:
func StartFileServer() {
httpMux := http.NewServeMux()
httpMux.HandleFunc("/abc/", basicAuth(handle))
http.ListenAndServe(":8000", &slashFix{httpMux})
}
func handle(writer http.ResponseWriter, r *http.Request) {
dirName := "C:\\Users\\gayr\\GolandProjects\\src\\NDAC\\download\\"
http.StripPrefix("/abc",
http.FileServer(http.Dir(dirName))).ServeHTTP(writer, r)
}
func basicAuth(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if user != "UserName" || pass != "Password" {
w.WriteHeader(401)
w.Write([]byte("Unauthorised.\n"))
return
}
handler(w, r)
}
}
我遇到了如下实例来测试 http 处理程序:
req, err := http.NewRequest("GET", "/abc/testfile.txt", nil)
if err != nil {
t.Fatal(err)
}
req.SetBasicAuth("UserName", "Password")
rr := httptest.NewRecorder()
handler := http.HandlerFunc(basicAuth(handle))
handler.ServeHTTP(rr, req)
这样做会调用使用 http.HandleFunc 实现的 ServeHTTP 函数,但我希望调用在我的代码中实现的 ServeHTTP。如何做到这一点?另外,有没有办法让我直接测试 StartFileServer()?
编辑:我检查了评论中提供的链接;我的问题似乎不是重复的。我有一个具体的问题:我希望调用在我的代码中实现的 ServeHTTP,而不是调用使用 http.HandleFunc 实现的 ServeHTTP 函数。我在提供的链接中没有看到这个问题。
解决方案
http.HandlerFunc 实现了 http.Handler。正如 Flimzy 在评论中指出的那样,basicAuth 不需要 HandlerFunc;任何 http.Handler 都可以。坚持使用 http.Handler 接口而不是具体的 HandlerFunc 类型将使一切都易于组合:
func basicAuth(handler http.Handler) http.Handler { // Note: http.Handler, not http.HandlerFunc
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok {
// TODO
}
if user != "UserName" || pass != "Password" {
w.WriteHeader(401)
w.Write([]byte("Unauthorised.\n"))
return
}
handler.ServeHTTP(w, r)
})
}
func TestFoo(t *testing.T) {
req, err := http.NewRequest("GET", "/abc/testfile.txt", nil)
if err != nil {
t.Fatal(err)
}
req.SetBasicAuth("UserName", "Password")
rr := httptest.NewRecorder()
// composition is trivial now
sf := &slashFix{
mux: http.HandlerFunc(handle),
}
handler := basicAuth(sf)
handler.ServeHTTP(rr, req)
// assert correct rr
}
推荐阅读
- python - str.readline() 带有彩色标准输出 catchstartswith()
- java - Spring Security:工件部署期间的错误由
和 web.xml 中的部分 - python - Python:在文本文件中查找一个字符串,如果同一行中的整数> 1,则打印它
- r - 如何在 R 中获得 PCA 结果
- html - Outlook Windows 10 中 html 电子邮件中的空白
- c# - MassTransit - InMemoryTestHarness 和优先消息传递
- css - @font-face 仅适用于 iOS 上的 Chrome 和 Firefox
- r - 使用 for 循环向多个数据框添加新列
- linux - 不能使用 pip3,给我错误
- swift - Swift Combine removeDuplicates() 未按预期工作