2016-09-18 236 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現在我明白了 –

相關問題