Go HTTP 客户端最小示例
此示例从 TechOverflow 的 IP 地址 HTTP API 获取当前 IPv4 地址如何使用 wget 获取你当前的 IPv4 地址。
go_http_client_example.go
package main
import (
"io/ioutil"
"net/http"
)
func main() {
// 执行请求
resp, err := http.Get("https://ipv4.techoverflow.net/api/get-my-ip")
if err != nil {
print(err)
return
}
// 此函数结束时清理
defer resp.Body.Close()
// 将所有响应数据读取到 []byte
body, err := ioutil.ReadAll(resp.Body)
// 解码并打印
println(string(body))
}保存为 Main.go 在新的项目目录中(例如 GoHttpTest)并在该目录中运行 go build。
之后,你可以运行 ./GoHttpTest,它应该打印你的 IPv4 地址。示例:
go_http_client_build_and_run.sh
uli@server ~/GoHttpTest % go build
uli@server ~/GoHttpTest % ./GoHttpTest
91.59.80.56If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow