2

I use goroutines achieve http.Get timeout, and then I found that the number has been rising steadily goroutines, and when it reaches 1000 or so, the program will exit

Code:

package main

import (
        "errors"
        "io/ioutil"
        "log"
        "net"
        "net/http"
        "runtime"
        "time"
)

// timeout dialler
func timeoutDialler(timeout time.Duration) func(network, addr string) (net.Conn, error) {
        return func(network, addr string) (net.Conn, error) {
                return net.DialTimeout(network, addr, timeout)
        }
}

func timeoutHttpGet(url string) ([]byte, error) {
        // change dialler add timeout support && disable keep-alive
        tr := &http.Transport{
                Dial:              timeoutDialler(3 * time.Second),
                DisableKeepAlives: true,
        }

        client := &http.Client{Transport: tr}

        type Response struct {
                resp []byte
                err  error
        }

        ch := make(chan Response, 0)
        defer func() {
                close(ch)
                ch = nil
        }()

        go func() {
                resp, err := client.Get(url)
                if err != nil {
                        ch <- Response{[]byte{}, err}
                        return
                }
                defer resp.Body.Close()

                body, err := ioutil.ReadAll(resp.Body)
                if err != nil {
                        ch <- Response{[]byte{}, err}
                        return
                }

                tr.CloseIdleConnections()
                ch <- Response{body, err}
        }()

        select {
        case <-time.After(5 * time.Second):
                return []byte{}, errors.New("timeout")
        case response := <-ch:
                return response.resp, response.err
        }
}

func handler(w http.ResponseWriter, r *http.Request) {
        _, err := timeoutHttpGet("http://google.com")
        if err != nil {
                log.Println(err)
                return
        }
}

func main() {
        go func() {
                for {
                        log.Println(runtime.NumGoroutine())
                        time.Sleep(500 * time.Millisecond)
                }
        }()

        s := &http.Server{
                Addr:         ":8888",
                ReadTimeout:  15 * time.Second,
                WriteTimeout: 15 * time.Second,
        }

        http.HandleFunc("/", handler)
        log.Fatal(s.ListenAndServe())
}

http://play.golang.org/p/SzGTMMmZkI

4

1 回答 1

3

用 1 而不是 0 初始化你的 chan:

ch := make(chan Response, 1)

并删除关闭和消除 ch 的延迟块。

见:http: //blog.golang.org/go-concurrency-patterns-timing-out-and

这是我认为正在发生的事情:

  1. 5s超时后,timeoutHttpGet返回
  2. defer 语句运行,关闭 ch 然后将其设置为 nil
  3. 它开始执行实际获取的 go 例程完成并尝试将其数据发送到 ch
  4. 但是 ch 为 nil,因此不会收到任何内容,从而阻止该语句完成,从而阻止 go 例程完成

我假设您正在设置ch = nil,因为在您设置之前,您会遇到运行时恐慌,因为当您尝试写入封闭通道时会发生这种情况,如规范所述。

给 ch 一个缓冲区 1 意味着 fetch go 例程可以在不需要接收器的情况下发送给它。如果处理程序由于超时而返回,那么稍后一切都会被垃圾收集。

于 2014-01-08T08:47:15.910 回答