You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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,
}
}