在线文档  >   Golang练习   >   HTTP 客户端

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

package main

import (
    "bufio"
    "fmt"
    "net/http"
)

func main() {

    // 向服务器发出一个 HTTP GET 请求。
    // `http.Get` 是在创建 `http.Client` 对象并调用其 `Get` 方法周围的便捷快捷方式;
    // 它使用 `http.DefaultClient` 对象,该对象具有有用的默认设置。
    resp, err := http.Get("https://gobyexample.com")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // 打印 HTTP 响应状态。
    fmt.Println("Response status:", resp.Status)

    // 打印响应体的前 5 行。
    scanner := bufio.NewScanner(resp.Body)
    for i := 0; scanner.Scan() && i < 5; i++ {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        panic(err)
    }
}

运行结果如下:

$ go run http-clients.go
Response status: 200 OK


  
    
    Go by Example