关于go:go使用nethttp库发送GET请求

29次阅读

共计 860 个字符,预计需要花费 3 分钟才能阅读完成。

一、概述

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))
}

2.2 封装 header 以及 param 参数

正文完
 0