在Golang中,可以使用net/http包来建立HTTP连接。以下是一个简单的示例:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err := http.Get("https://example.com")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
}
这个示例使用http.Get方法发送GET请求到指定的URL(例如”https://example.com”),并获取响应。通过resp.Body读取响应的主体内容,并将其打印出来。
当然,在实际开发中,还可以使用http.NewRequest方法创建自定义的HTTP请求,以及设置请求头、参数等更多选项。但以上示例展示了最基本的HTTP连接操作。
内容由零声教学AI助手提供,问题来源于学员提问




