The following code is an Http connection pool implemented using the net/http package, and the complete code is at the end
Article Directory
Create a connection pool
Initialize connection pool properties
Description of common attributes:
Attributes | illustrate |
---|---|
Dial | (Deprecated) Provides methods for creating unencrypted TCP connections |
DialContext | Provides a method for creating an unencrypted TCP connection. If both DialContext and Dial are not set, the dial function under the net package will be used by default. |
DialTLS | (Deprecated) Provides methods for creating TLS requests for non-proxy HTTPS |
DialTLSContext | After the method setting for creating non-proxy HTTPS TLS requests is provided , the HTTPS requests will not use the related configurations of DialContext and Dial. If neither DialTLSContext nor DialTLS is set, the configurations of DialContext and TLSClientConfig will be used by default. |
TLSClientConfig | Specifies the TLS configuration to use with |
TLSHandshakeTimeout | TLS connection handshake timeout |
DisableKeepAlives | If set to true, a connection can only be used by one request and cannot be reused |
DisableCompression | If set to true prevents the transport from requesting compression with "Accept Encoding: gzip" |
MaxIdleConns | The maximum number of idle connections allowed by all hosts |
MaxIdleConnsPerHost | The maximum number of idle connections allowed by a single host, if set to 0, use the default value of 2 |
MaxConnsPerHost | The maximum number of connections allowed by a single host, setting 0 means unlimited |
IdleConnTimeout | Connection survival time, setting 0 means unlimited |
ResponseHeaderTimeout | Response header receiving timeout length, does not include the response body |
MaxResponseHeaderBytes | Response header content length maximum limit, set 0 to use the default limit |
WriteBufferSize | Specify the size of the write buffer used when writing the transfer, set to 0 and default to 4KB |
ReadBufferSize | Specifies the size of the read buffer used when reading from the transfer, set to 0 and default to 4KB |
ForceAttemptHTTP2 | true to use HTTP2 (if Dial or DialTLS or DialContext method is configured or TLSClientConfig configuration is provided) |
Create and initialize a connection pool
structure
In most cases, the interface we request needs to carry various request header information, such as cookies.
Store the request header information in the structure instance, and subsequent requests initiated by this instance will have the same request header information.
GET method
If we don’t need any request header information, we can directly use httpClient.Get to request the interface.
If we want to set the request header information, we must first use http.NewRequest to declare a request, insert the Header data and finally execute it by httpClient.
After receiving the response, the processing result is that we must remember to close the response stream in time
POST method
Similar to the Get method, we usually pass the request body in the POST request. The processing of the request body is as follows:
full code
package cus_http
import (
"bytes"
"encoding/json"
"io/ioutil"
"net"
"net/http"
"time"
)
// 初始化连接池配置
var httpTrans = &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100, //所有Host的连接池最大空闲连接数
MaxIdleConnsPerHost: 2, //每个Host的连接池最大空闲连接数
MaxConnsPerHost: 4, //每个Host的连接池最大连接数
IdleConnTimeout: time.Duration(90000) * time.Millisecond, //空闲连接保留时间
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
// 初始化连接池
var httpClient = &http.Client{
Timeout: 30 * time.Second,
Transport: httpTrans,
}
type CusHttp struct {
Header map[string]string
}
// 发送GET请求
// url: 请求地址
func (cus *CusHttp) Get(url string) string {
// resp, err := httpClient.Get(url)
//初始化请求
reqest, err := http.NewRequest("GET", url, nil)
//增加Header选项
if cus.Header != nil && len(cus.Header) > 0 {
for k, vla := range cus.Header {
reqest.Header.Add(k, vla)
}
}
if err != nil {
panic(err)
}
resp, err := httpClient.Do(reqest)
if err != nil {
panic(err)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
return string(result)
}
// 发送POST请求 默认使用
// url: 请求地址
// data: POST请求提交的数据
func (cus *CusHttp) Post(url string, data interface{
}) string {
return cus.post(url, data)
}
// 发送POST 表单
// url: 请求地址
// data: POST请求提交的数据
func (cus *CusHttp) PostForm(url string, data interface{
}) string {
cus.Header["Content-Type"] = "application/x-www-form-urlencoded"
return cus.post(url, data)
}
// 发送POST请求
// url: 请求地址
// data: POST请求提交的数据
func (cus *CusHttp) post(url string, data interface{
}) string {
jsonStr, _ := json.Marshal(data)
//初始化请求
reqest, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
//增加Header选项
if cus.Header != nil && len(cus.Header) > 0 {
for k, vla := range cus.Header {
reqest.Header.Add(k, vla)
}
}
if err != nil {
panic(err)
}
resp, err := httpClient.Do(reqest)
if err != nil {
panic(err)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
return string(result)
}
test
result