Go by Example: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.dev.org.tw")
    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
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Go by Example</title>

下一個範例:HTTP 資訊服務提供方