使用 Golang 实现,打印 http 返回的状态码。(Go 语言圣经书后习题 1.9)
修改 fetch 打印出 HTTP 协议的状态码,可以从 resp.Status 变量 得到该状态码。
我们得到 http 请求的返回后,直接打印其 Status 属性即可。
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
for _, url := range os.Args[1:] {
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stdin, "fetch: %v\n", err)
os.Exit(1)
}
b := resp.Status
fmt.Printf("%s", b)
}
}
我们输入以下命令行,开始运行程序:
go run haicoder.go http://www.haicoder.net
程序运行后,控制台输出如下:
我们可以看到,我们的程序输出了 http 请求返回的状态码,我们只需要在拿到 http 请求的返回后,打印出其 Status 属性即可。