Go HTTP Client 持久连接

https://serholiu.com/go-http-client-keepalive

 

package main

import (
    "crypto/tls"
    "io/ioutil"
    "log"
    "net/http"
    "strings"
)

func main() {
    c := NewClient("http://127.0.0.1:8080/get")
    r, e := c.HttpGetRequest()
    if e != nil {
        log.Fatalln(e)
    }
    log.Println(string(r))
}

// Client 定义一个结构体
type Client struct {
    url    string
    client *http.Client
}

func NewClient(url string) *Client {
    return &Client{
        url: url,
        client: &http.Client{
            Transport: &http.Transport{
                MaxIdleConnsPerHost: 100, // 每台主机保持的最大空闲连接
                MaxConnsPerHost:     100, // 限制每个主机的连接总数
                //初始化client支持的http协议, 并在tls握手时告知server
                TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
            },
        },
    }
}

// HttpGetRequest http请求
func (c *Client) HttpGetRequest() (resBody []byte, err error) {

    // 初始化请求
    req, err := http.NewRequest("GET", c.url, nil)
    if err != nil {
        return nil, err
    }

    // 执行请求
    req.Header.Add("Content-Type", "application/json")
    res, err := c.client.Do(req)
    if err != nil {
        return nil, err
    }
    defer res.Body.Close()

    // 接收返回结果
    resBody, err = ioutil.ReadAll(res.Body)
    if err != nil {
        return nil, err
    }
    return resBody, nil
}

// HttpRequest http请求
func (c *Client) HttpRequest(params string) (resBody []byte, err error) {
    // 初始化请求
    body := strings.NewReader(params)
    req, err := http.NewRequest("POST", c.url, body)
    if err != nil {
        return nil, err
    }
    // 执行请求
    req.Header.Add("Content-Type", "application/json")
    res, err := c.client.Do(req)
    if err != nil {
        return nil, err
    }
    defer res.Body.Close()
    // 接收返回结果
    resBody, err = ioutil.ReadAll(res.Body)
    if err != nil {
        return nil, err
    }
    return resBody, nil
}

 

posted @ 2022-09-08 11:26  许伟强  阅读(224)  评论(0编辑  收藏  举报