http 包 提供了 HTTP 客户端实现,和服务端的实现。 通过 http 包,我们可以发送网络请求,get, post 等。
构建 get , 方法,很简单,示例:
resp, err := http.Get("http://example.com/")
...
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
...
resp, err := http.Post("h ttp://example.com/upload", "image/jpeg", &buf)
在使用完毕后,记得一定要关闭,像下面这样:
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get("http://example.com")
// ...
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: pool},
DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
Clients 和 Transports 是通过 go程 的安全并发实现,高效一点的方法是:创建一个,多次重用它。
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func demoGet(){
resp,err := http.Get("http://www.baidu.com")
defer resp.Body.Close()
if err != nil {
fmt.Println("ERROR: ",err);
return
}
fmt.Println(resp);
body,_ := ioutil.ReadAll(resp.Body)
fmt.Print(string(body))
}
func main() {
demoGet()
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有