如何使用SingleFlight共享下载的大文件?

时间:2019-04-05 18:00:58

标签: go

我正在通过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都可以

  1. 至少从自己的reponseWriter看结果
  2. 超时与r1

1 个答案:

答案 0 :(得分:0)

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