GolangNote

Golang笔记

golang 标准包 http 实现HTTP 客户端和服务端的功能

Permalink

golang 标准包 http 可提供HTTP 客户端和服务端的功能。

golang 标准包 http

客户端

可发起http 或 https 的 Get, Head, Post 和 PostForm 请求:

Go: Get,Head,Post,PostForm 请求
1
2
3
4
5
6
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
    url.Values{"key": {"Value"}, "id": {"123"}})

客户端必须在请求结束后关闭:

Go: 关闭resp.Body
1
2
3
4
5
6
resp, err := http.Get("http://example.com/")
if err != nil {
    // handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

还可以做更复杂的请求,比如添加headers , 重定向等设置:

Go: 带Header请求
1
2
3
4
5
6
7
8
9
10
11
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)

通过代理请求:

Go: 代理请求
1
2
3
4
5
6
tr := &http.Transport{
    TLSClientConfig:    &tls.Config{RootCAs: pool},
    DisableCompression: true,
}
client := &http.Client{Transport: tr}
    resp, err := client.Get("https://example.com")

启动一个简单的服务器:

Go: 启动服务器
1
2
3
4
5
6
7
http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

log.Fatal(http.ListenAndServe(":8080", nil))

复杂一点的服务:

Go: server
1
2
3
4
5
6
7
8
s := &http.Server{
    Addr:           ":8080",
    Handler:        myHandler,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())

官方文档 net/http

本文网址: https://golangnote.com/topic/10.html 转摘请注明来源

Related articles

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Write a Comment to "golang 标准包 http 实现HTTP 客户端和服务端的功能"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms