【发布时间】:2018-06-21 18:37:19
【问题描述】:
我正在尝试为我的 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()?
编辑:我检查了 cmets 中提供的链接;我的问题似乎不是重复的。我有一个具体的问题:我希望调用在我的代码中实现的 ServeHTTP,而不是调用使用 http.HandleFunc 实现的 ServeHTTP 函数。我没有在提供的链接中看到这个问题。
【问题讨论】:
-
我检查了上面提供的链接;我的问题似乎不是重复的。我有一个具体的问题:我希望调用在我的代码中实现的 ServeHTTP,而不是调用使用 http.HandleFunc 实现的 ServeHTTP 函数。
-
回答完毕。只需传递您的
slashFix类型的实例,因为它已经是http.Handler。 -
传递 slashFix 的实例(遵循这个答案:stackoverflow.com/a/37549527/5772695)调用我实现的 ServeHTTP,但我如何将它与文件服务部分的 basicAuth(handle) 结合起来?没有这个,我得到“恐慌:运行时错误:无效的内存地址或零指针取消引用”
-
basicAuth应该使用http.Handler而不是http.HandlerFunc,这样会很容易。
标签: unit-testing http go