【问题标题】:Why does http.Get result in two requests instead of one?为什么 http.Get 会导致两个请求而不是一个?
【发布时间】: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期间执行。
  • 好的,没问题,有人将其标记为离题吗?

标签: http testing go server


【解决方案1】:

http.FileServer() 就是这样写的。引用其文档:

作为一种特殊情况,返回的文件服务器会将任何以“/index.html”结尾的请求重定向到相同的路径,而不是最终的“index.html”。

这就是你所经历的:你在请求/bower_components/index.html,所以http.FileServer()返回的处理程序发送了一个重定向:

HTTP/1.1 301 Moved Permanently
Location: ./

并且http.Get() 表现良好,遵循此重定向,并执行另一个HTTP GET,现在没有index.htmlhttp.FileServer() 处理程序将尝试在这种情况下提供index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    相关资源
    最近更新 更多