|
|
package HttpUtil
|
|
|
|
|
|
import (
|
|
|
"github.com/valyala/fasthttp"
|
|
|
"net"
|
|
|
"net/http"
|
|
|
"time"
|
|
|
)
|
|
|
|
|
|
var HttpClient *http.Client
|
|
|
var err error
|
|
|
|
|
|
//go get -u github.com/valyala/fasthttp
|
|
|
//参考:https://blog.csdn.net/Guo_Mao_Zhen/article/details/100936779
|
|
|
func FastHttpPost(url string, body string) (string, error) {
|
|
|
req := fasthttp.AcquireRequest()
|
|
|
defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
|
|
|
// 默认是application/x-www-form-urlencoded
|
|
|
req.Header.SetContentType("application/json")
|
|
|
req.Header.SetMethod("POST")
|
|
|
req.SetRequestURI(url)
|
|
|
req.SetBody([]byte(body))
|
|
|
resp := fasthttp.AcquireResponse()
|
|
|
defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源
|
|
|
err := fasthttp.Do(req, resp)
|
|
|
if err!=nil{
|
|
|
return "发生严重错误!",err
|
|
|
}else{
|
|
|
return string(resp.Body()), nil
|
|
|
}
|
|
|
}
|
|
|
|
|
|
func init() {
|
|
|
HttpClient = &http.Client{}
|
|
|
HttpClient.Transport = &http.Transport{
|
|
|
Proxy: http.ProxyFromEnvironment,
|
|
|
DialContext: (&net.Dialer{
|
|
|
Timeout: 60 * time.Second,
|
|
|
KeepAlive: 60 * time.Second, //开启长连接
|
|
|
}).DialContext,
|
|
|
DisableCompression: true,
|
|
|
MaxIdleConns: 100, //最大空闲连接数
|
|
|
MaxIdleConnsPerHost: 100, //100个连接池大小
|
|
|
IdleConnTimeout: 90 * time.Second, //连接最大空闲时间
|
|
|
TLSHandshakeTimeout: 10 * time.Second,
|
|
|
ExpectContinueTimeout: 1 * time.Second,
|
|
|
}
|
|
|
}
|