# 12.9 Go实现web客户端

在这节，将学习更多关于使用 Go 开发 web 客户端。这个 web 客户端工具的名字是 `webClient.go`，分为四部分展示。

`webClient.go` 的第一部分包含如下代码：

```go
package main

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

`webClient.go` 的第二部分是读取命令行参数获得期望的 URL：

```go
func main() {
    if len(os.Args) != 2 {
        fmt.Printf("Usage: %s URL\n", filepath.Base(os.Args[0]))
        return
    }

    URL := os.Args[1]
```

`webClient.go` 的第三部分是实际操作发生的地方：

```go
    data, err := http.Get(URL)

    if err != nil {
        fmt.Println(err)
        return
```

`http.Get()` 调用做了所有的工作，当您不想要处理参数和选项时它是相当的方便。然而，这样的调用方式在处理过程中没有灵活性。注意，`http.Get()` 返回一个 `http.Response` 变量。

余下的代码如下：

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

上面这段代码复制 `http.Response` 结构的 `Body` 字段内容到标准输出。

执行 `webClient.go` 将产生如下输出：

> *只有已小部分展示在这*

![](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/images/chapter12/12.9.jpg)

`webClient.go` 的主要问题是几乎不能控制处理过程——您要么获得全部 HTML 输出，要么什么都没有！


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/12.0/12.9.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
