> For the complete documentation index, see [llms.txt](https://wskdsgcf.gitbook.io/mastering-go-zh-cn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wskdsgcf.gitbook.io/mastering-go-zh-cn/12.0/12.10.md).

# 12.10 HTTP连接超时

这节将介绍一个处理网络连接超时的技巧，网络连接超时是花了太长的时间也没有连接上。记住您已经知道了一个技巧，是从[第十章](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter10/10.0.md)（Go 并发-进阶讨论），我们讨论 `context` 标准包时学到的。这个技巧展示在 `useContext.go` 源码文件中。

在这节介绍的方法实现起来非常简单。相关代码保存在 `clientTimeOut.go` 文件中，分为四个部分来介绍。这个程序接收俩个命令行参数，一个是 URL 另一个是超时秒数。注意第二个参数是可选的。

`clientTimeOut.go` 的第一部分如下：

```go
package main

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

var timeout = time.Duration(time.Second)
```

`clientTimeOut.go` 的第二段代码如下：

```go
func Timeout(network, host string) (net.Conn, error) {
    conn, err := net.DialTimeout(network, host,timeout)
    if err != nil {
        return nil, err
    }
    conn.SetDeadline(time.Now().Add(timeout))
    return conn, nil
}
```

在下节，您将学习更多关于 `SetDeadline()` 的功能。`Timeout()` 函数用在 `http.Transport` 变量的 `Dial` 字段。

`clientTimeOut.go` 的第三部分代码如下：

```go
func main() {
    if len(os.Args) == 1 {
        fmt.Printf("Usage: %s URL TIMEOUT\n", filepath.Base(os.Args[0]))
        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]
    t := http.Transport{
        Dial: Timeout,
    }
```

`clientTimeOut.go` 的其余代码如下：

```go
    client := http.Client {
        Transport: &t,
    }

    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
        }
    }
}
```

使用在[第十章](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter10/10.0.md)（Go 并发-进阶讨论）开发的 `slowWWW.go` web 服务器测试`clientTimeOut.go` web 客户端。

执行 `clientTimeOut.go` 俩次将产生如下输出：

```
$ go run clientTimeOut.go http://localhost:8001
Serving: /
Delay:  0
$ go run clientTimeOut.go http://localhost:8001
Get http://localhost:8001: read tcp[::1]:57397->[::1]:8001: i/o timeout
```

从上面的输出您能看出，第一个请求连接所期望的 web 服务器没有问题。然而，第二个 `http.Get()` 请求花的时间比预期长，所以超时了！
