一、概述
http 包提供 HTTP 客户端和服务器实现。
官网文档 https://pkg.go.dev/net/http 咱们能够多看几遍。
次要的提供的办法有 Get、Head、Post 和 PostForm 。
咱们实现的话get申请的话,次要有2种形式
http.Get()client.Get()
而后咱们会介绍封装参数,header,transport
二、2种实现形式
2.1 最简略的 http.Get()办法
咱们应用http的Get()函数
func Get(url string ) (resp * Response , err error )
Get办法 向指定的 URL 收回 GET。
Get 是 DefaultClient.Get 的包装器。用于没有自定义header的疾速申请。
func Test1(t *testing.T) { url := fmt.Sprintf("http://localhost:8080/v1/user?id=%d", 1010) resp, err := http.Get(url) if err != nil { } // 客户端发动的申请必须在完结的时候敞开 response body defer resp.Body.Close() body, err := io.ReadAll(resp.Body) t.Log(resp, err) t.Log(string(body))}
这个代码,咱们能够等价替换为DefaultClient.Get如下
func Test1t(t *testing.T) { url := fmt.Sprintf("http://localhost:8080/v1/user?id=%d", 1010) resp, err := http.DefaultClient.Get(url) if err != nil { } // 客户端发动的申请必须在完结的时候敞开 response body defer resp.Body.Close() body, err := io.ReadAll(resp.Body) t.Log(resp, err) t.Log(string(body))}