如何在 Golang 中獲取響應狀態碼?


響應狀態碼是在我們收到響應時獲得的數字,它表示當我們向伺服器請求某些內容時,我們從伺服器收到的響應型別。

從響應中可以獲得不同的狀態碼,這些狀態碼主要分為五類。

通常,狀態碼被分為以下五類。

  • 1xx (資訊類)

  • 2xx (成功類)

  • 3xx (重定向類)

  • 4xx (客戶端錯誤類)

  • 5xx (伺服器錯誤類)

在這篇文章中,我們將嘗試獲取其中兩個或多個狀態碼。

示例 1

讓我們從對 **google.com** URL 的基本 HTTP 請求開始。完成後,我們將從伺服器獲取響應,該響應將包含狀態碼。

請考慮以下程式碼。

package main

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

func main() {
   resp, err := http.Get("https://www.google.com")
   if err != nil {
      log.Fatal(err)
   }

   fmt.Println("The status code we got is:", resp.StatusCode)
}

輸出

如果我們在上述程式碼上執行命令 **go run main.go**,那麼我們將在終端中獲得以下輸出。

The status code we got is: 200

示例 2

每個狀態碼還包含一個 **StatusText**,我們也可以使用 **statusCode** 列印它。

請考慮以下程式碼。

package main

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

func main() {
   resp, err := http.Get("https://www.google.com")
   if err != nil {
      log.Fatal(err)
   }

   fmt.Println("The status code we got is:", resp.StatusCode)
   fmt.Println("The status code text we got is:", http.StatusText(resp.StatusCode))
}

輸出

如果我們在上述程式碼上執行命令 **go run main.go**,那麼我們將在終端中獲得以下輸出。

The status code we got is: 200
The status code text we got is: OK

示例 3

我們能夠獲取狀態碼 200,因為該 URL 在當時可用。如果我們對一個未啟用的 URL 發出請求,我們將收到 404 狀態碼。

請考慮以下程式碼。

package main

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

func main() {
   resp, err := http.Get("https://www.google.com/apple")
   if err != nil {
      log.Fatal(err)
   }

   fmt.Println("The status code we got is:", resp.StatusCode)
   fmt.Println("The status code text we got is:", http.StatusText(resp.StatusCode))
}

輸出

如果我們在上述程式碼上執行命令 **go run main.go**,那麼我們將在終端中獲得以下輸出。

The status code we got is: 404
The status code text we got is: Not Found

更新於: 2021年11月1日

13K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.