创建测试文件./bower_components/index.html
并在./
中运行go test
。为什么http.Get会产生两个请求而不是一个?
为什么下面打印两行而不是第一行?
./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的仓库,所以你可以运行去测试命令,看看我的意思。
但通过http.Get请求favicon没有任何意义吗? –
对不起。错过它在'go test'期间执行。 – Volker
好的没问题,ps有人将此标记为脱离主题? –