Golang 如何获取响应状态代码
响应状态码是我们在响应中得到的数字,它标志着当我们向服务器提出要求时,我们从它那里得到了什么类型的响应。
从响应中得到的状态码有很多,主要分为五类。
一般来说,状态代码被分为这五类。
- 1xx (信息性)
-
2xx (成功)
-
3xx (重定向)
-
4xx (客户端错误)
-
5xx (服务器错误)
在本文中,我们将尝试获得两个或多个这样的状态代码。
例子1
让我们从对 google.com 网址的基本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
极客教程