golang http超时和goroutines积累

时间:2014-01-08 08:25:13

标签: http go goroutine

我使用goroutines实现http.Get超时,然后我发现该数字一直在稳步上升goroutines,当它达到1000左右时,程序将退出

代码:

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

1 个答案:

答案 0 :(得分:3)

用1而不是0来启动你的陈:

ch := make(chan Response, 1)

删除关闭的延迟块,然后删除ch。

请参阅:http://blog.golang.org/go-concurrency-patterns-timing-out-and

以下是我的想法:

  1. 在5s超时后,timeoutHttpGet返回
  2. 延迟语句运行,关闭ch然后将其设置为nil
  3. go例程它开始执行实际的获取完成并尝试将其数据发送到ch
  4. 但是ch是零,所以不会收到任何东西,阻止该陈述完成,从而阻止完成常规
  5. 我假设您正在设置ch = nil,因为在此之前,您会遇到运行时恐慌,因为当您尝试写入已关闭的频道时会发生这种情况,如the spec所述。< / p>

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