【发布时间】:2017-01-26 12:18:22
【问题描述】:
创建一个测试文件./bower_components/index.html 并在./ 中运行go test。
为什么下面会打印两行而不是第一行?
./bower_components/index.html
./bower_components/
输出:
=== RUN TestRootHandler
./bower_components/index.html
./bower_components/ ???
--- PASS: TestRootHandler (0.00s)
main_test.go:32: 200 - ./bower_components/Hello World.html
PASS
ok
代码:
// RootHandler for HTTP
func RootHandler(root string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := os.Open(root + r.URL.Path)
if err != nil {
fmt.Println(err.Error())
h.ServeHTTP(w, r)
return
}
fmt.Println(root + r.URL.Path)
r.URL.Path = root + r.URL.Path
h.ServeHTTP(w, r)
})
}
// TestRootHandler
func TestRootHandler(t *testing.T) {
ts := httptest.NewServer(RootHandler("./bower_components", http.FileServer(http.Dir("./"))))
defer ts.Close()
res, err := http.Get(ts.URL + "/index.html")
if err != nil {
t.Fatal(err)
}
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
}
t.Logf("%d - %s", res.StatusCode, body)
}
如果你不明白这个问题,请告诉我,然后我会设置一个 github 存储库,这样你就可以运行 go test 命令来了解我的意思。
【问题讨论】:
-
但是通过 http.Get 请求 favicon 没有意义吧?
-
对不起。错过了它在
go test期间执行。 -
好的,没问题,有人将其标记为离题吗?