HTTP Clients {.en}

HTTP客户端 {.zh}

::: {.en} The Go standard library comes with excellent support for HTTP clients and servers in the net/http package. In this example we’ll use it to issue simple HTTP requests. :::

::: {.zh}

Go标准库为net / httppackage中的HTTP客户端和服务器提供了出色的支持。在这个例子中,我们将使用它来发出简单的HTTP请求。

:::

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net/http"
  6. )
  7. func main() {

::: {.en} Issue an HTTP GET request to a server. http.Get is a convenient shortcut around creating an http.Client object and calling its Get method; it uses the http.DefaultClient object which has useful default settings. :::

::: {.zh}

向服务器发出HTTP GET请求。 http.Get是创建http.Clientobject并调用其Get方法的简便快捷方式;它使用http.DefaultClient对象,该对象具有有用的默认设置。

:::

  1. resp, err := http.Get("http://gobyexample.com")
  2. if err != nil {
  3. panic(err)
  4. }
  5. defer resp.Body.Close()

::: {.en} Print the HTTP response status. :::

::: {.zh}

打印HTTP响应状态。

:::

  1. fmt.Println("Response status:", resp.Status)

::: {.en} Print the first 5 lines of the response body. :::

::: {.zh}

打印响应正文的前5行。

:::

  1. scanner := bufio.NewScanner(resp.Body)
  2. for i := 0; scanner.Scan() && i < 5; i++ {
  3. fmt.Println(scanner.Text())
  4. }
  5. if err := scanner.Err(); err != nil {
  6. panic(err)
  7. }
  8. }
  1. $ go run http-clients.go
  2. Response status: 200 OK
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <meta charset="utf-8">
  7. <title>Go by Example</title>