我正在通过singleflight代理一堆http GET调用。但是返回的响应仅在第一个请求中可见。

我在测试中也注意到了一个问题。如果第一个请求超时,则响应将丢失。

假设r1,r2,r3是顺序出现的请求。它们全部分组为一个groupKey。如果r1超时,r2r3将等待,直到共享的HTTP调用返回或直到它们自己的超时为止。

代理代码(贷记here)

// add auth to the requst and proxy to target host
var serveReverseProxy = func(target string, res http.ResponseWriter, req *http.Request) {
    log.Println("new request!")
    requestURL, _ := url.Parse(target)
    proxy := httputil.NewSingleHostReverseProxy(requestURL)
    req1, _ := http.NewRequest(req.Method, req.RequestURI, req.Body)
    for k, v := range req.Header {
        for _, vv := range v {
            req1.Header.Add(k, vv)
        }
    }
    req1.Header.Set("Authorization", "Bearer "+"some token")
    req1.Host = requestURL.Host

    proxy.ServeHTTP(res, req1)
}

var requestGroup singleflight.Group
mockBackend := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
    groupKey := req.Host + req.RequestURI
    name := req.Header.Get("From")
    ch := requestGroup.DoChan(groupKey, func() (interface{}, error) {
        //increase key retention to 20s to make sure r1,r2,r3 are all in one group
        go func() {
            time.Sleep(20 * time.Second)
            requestGroup.Forget(groupKey)
            log.Println("Key deleted :", groupKey)
        }()

        // proxy to some host and expect the result to be written in res
        serveReverseProxy("https://somehost.com", res, req)
        return nil, nil
    })

    timeout := time.After(15 * time.Second)

    var result singleflight.Result
    select {
    case <-timeout: // Timeout elapsed, send a timeout message (504)
        log.Println(name, " timed out")
        http.Error(res, "request timed out", http.StatusGatewayTimeout)
        return
    case result = <-ch: // Received result from channel
    }

    if result.Err != nil {
        http.Error(res, result.Err.Error(), http.StatusInternalServerError)
        return
    }

    if result.Shared {
        log.Println(name, " is shared")
    } else {
        log.Println(name, " not shared")
    }
}))

我希望r2r3都可以
  • 至少从自己的响应中看到结果
  • 超时以及r1
  • 最佳答案

    https://github.com/golang/net/blob/master/http2/h2demo/h2demo.go#L181-L219
    这可行。原来我需要在singleFlight.Group.Do中返回处理程序,而不是返回响应。
    我不知道为什么

    10-06 12:34