12.10.3 设置超时的另外一种方法

这小节将介绍另外一种从客户端处理 HTTP 连接超时的方法。如您所见,这是最简单的超时处理形式,因为您只需要定义一个 http.Client 对象并设置它的 Timeout 字段为期望的超时值。

展示最后一种超时类型的程序命名为 anotherTimeOut.go,并分为四个部分来介绍。

anotherTimeOut.go的第一部分如下:

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

var timeout = time.Duration(time.Second)

anotherTimeOut.go 的第二部分代码如下:

func main() {
    if len(os.Args) == 1 {
        fmt.Println("Please provide a URL")
        return
    }

    if len(os.Args) == 3 {
        temp, err := strconv.Atoi(os.Args[2])
        if err != nil {
            fmt.Println("Using Default Timeout!")
        } else {
            timeout = time.Duration(time.Duration(temp) * time.Second)
        }
    }

    URL := os.Args[1]

anotherTimeOut.go 的第三部分代码如下:

    client := http.Client{
        Timeout: timeout,
    }
    client.Get(URL)

这是使用 http.Client 变量的 Timeout 字段定义超时周期的地方。

anotherTimeOut.go 的最后一段代码如下:

    data, err := client.Get(URL)
    if err != nil {
        fmt.Println(err)
        return
    } else {
        defer data.Body.Close()
        _, err := io.Copy(os.Stdout, data.Body)
        if err != nil {
            fmt.Println(err)
            return
        }
    }
}

执行 anotherTimeOut.go 并和在第十章(Go 并发-进阶讨论)开发的 slowWWW.go web 服务器交互,将产生如下输出:

$ go run anotherTimeOut.go http://localhost:8001
Get http://localhost:8001: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
$ go run anotherTimeOut.go http://localhost:8001 15
Serving: /
Delay: 8

Last updated