• 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
    }
  • 相关阅读:
    sql--删除
    数据库--范式
    sql语句--插入
    sql--查询
    shapefile数据文件组成
    sql---应用
    sql语句 函数
    SWIG:Simple Wrapper and Interface Generator
    职责链模式
    mybatis 装饰模式【Executor】 缓存篇
  • 原文地址:https://www.cnblogs.com/xuweiqiang/p/16668872.html
Copyright © 2020-2023  润新知