2016-09-18 237 views
1

创建测试文件./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的仓库,所以你可以运行去测试命令,看看我的意思。

+0

但通过http.Get请求favicon没有任何意义吗? –

+0

对不起。错过它在'go test'期间执行。 – Volker

+0

好的没问题,ps有人将此标记为脱离主题? –

回答

7

这就是如何编写http.FileServer()的方式。从文档报价:

作为一个特殊的情况下,返回的文件服务器重定向在“/index.htm”明明相同的路径结束的任何请求,而最终“的index.html”。

这是你体验到什么:您请求/bower_components/index.html,所以通过http.FileServer()返回的句柄发送重定向:

HTTP/1.1 301 Moved Permanently 
Location: ./ 

而且http.Get()被乖巧,遵循此重定向,并执行其他HTTP GET,现在没有index.html,并且http.FileServer()处理程序将在这种情况下尝试并服务于index.html

+0

Aaaa谢谢你:D现在我明白了 –

相关问题