为什么httptest客户端忽略了环境?

时间:2018-03-08 15:01:00

标签: go proxy

我正在为我正在写的代理进行单元测试。我不能为我的生活看到为什么环境被忽略,我的测试直接访问目标服务器acap

func TestHandleHTTPS(t *testing.T) {
    successfulCalls := 0
    proxyPassed := 0

    acap := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        successfulCalls++
    }))
    defer acap.Close()

    testproxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        proxyPassed++
    }))
    defer testproxy.Close()
    os.Setenv("https_proxy", testproxy.URL)
    defer os.Setenv("https_proxy", "")

    client := acap.Client()
    tmp := client.Transport.(*http.Transport)
    tmp.Proxy = http.ProxyFromEnvironment // <--- This should make client use env vars!                                                                      

    req, err := http.NewRequest("GET", acap.URL, nil)
    if err != nil {
        t.Errorf("Unable to create request: %s", err.Error())
    }

    resp, err := client.Do(req)
    if err != nil {
        t.Errorf("Something is wrong with the test: %s", err.Error())
        return
    }

    if resp.StatusCode != 200 {
        t.Errorf("Unexpected status code: %d", resp.StatusCode)
        body, _ := ioutil.ReadAll(resp.Body)
        t.Errorf("Body: %s", string(body))
    }

    if successfulCalls == 0 {
        t.Errorf("No successful call over HTTPS occurred")
    }

    if proxyPassed == 0 {
        t.Errorf("Proxy got ignored")
    }
}

我唯一的失败是Proxy got ignored。我使用Go v1.10,一切都编译。

编辑1: 我做了tmp.Proxy舞蹈,因为客户已经在Transport中配置了证书和内容。我不想通过替换整个Transport结构

来搞砸它

1 个答案:

答案 0 :(得分:2)

如果你看一下doc for ProxyFromEnvironment,你会发现一个特例:

  

作为一种特殊情况,如果req.URL.Host是“localhost”(带或不带端口号),则会返回nil URL和nil错误。

这意味着不会使用任何代理。我建议你改用ProxyURL

proxyURL, _ := url.Parse(testproxy.URL)
tmp.Proxy = http.ProxyURL(proxyURL)

它将考虑您的代理,但不会工作,因为您正在尝试进行https调用抛出http代理...

相关问题