go 使用单例创建client,并复用
发布日期:2021-05-14 08:46:34 浏览次数:17 分类:精选文章

本文共 2572 字,大约阅读时间需要 8 分钟。

������������������������������������������������������������Web������������������������������������������������������������������Golang������������������������HTTP���������������������������������������������������������������HTTPS POST���������

���������������������������HTTP���������

���Golang������������������������once.Do������������������������������HTTP���������������������������������������������������CreateHTTPClient������������������������������������HTTP������������������������������������������������������������

���������������������������������������������

package main
import (
"github.com/cpuov/once"
"github.com/go-libs/http"
"github.com/go-libs/http/transport"
"net/http"
"time"
)
var (
httpClient *http.Client
once once.SyncOnce
)
func CreateHTTPClient() *http.Client {
once.Do(func() {
httpClient = &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 50000,
MaxIdleConnsPerHost: 50000,
IdleConnTimeout: 30 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSHandshakeTimeout: 3 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
})
return httpClient
}

���������������HTTPS POST������

������������������������HTTP������������������������������������HTTPS POST���������������������������������������

func HttpsPost(url, stu string, body *[]byte) []byte {
client := CreateHTTPClient()
reader := bytes.NewReader(stu)
request, err := http.NewRequest("POST", url, reader)
if err != nil {
return nil
}
request.Header.Set("Content-Type", "x-protobuf")
request.Header.Set("Connection", "Keep-Alive")
response, err := client.Do(request)
if err != nil {
return nil
}
defer response.Body.Close()
*body, _ = ioutil.ReadAll(response.Body)
return *body
}

���������������

  • ������HTTP������������������once���������������������������HTTP���������������������������������������������������������������������������
  • ������������������������������������������������������������DialContext���IdleConnTimeout���������������������������������������������������
  • ������������������TLS������������������InsecureSkipVerify: true������������ ������ ���������������������/testing���������
  • ������������������HTTP������������������Content-Type���Connection���������������������������������������������������
  • ������������������������������Golang���������������������������������HTTP���������������������������������������������HTTPS POST���������

    上一篇:Linux - firewalld - 开放端口 转载
    下一篇:php 导出.csv文件示例

    发表评论

    最新留言

    很好
    [***.229.124.182]2025年04月16日 12时22分05秒