123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package rdhttp
- import (
- "cockData/server/log"
- "fmt"
- "github.com/valyala/fasthttp"
- "strings"
- "sync"
- "time"
- )
- var client *fasthttp.Client
- func InitHttp() {
- readTimeout, _ := time.ParseDuration("300ms")
- writeTimeout, _ := time.ParseDuration("300ms")
- maxIdleConnDuration, _ := time.ParseDuration("8s")
- maxConnWaitTimeout, _ := time.ParseDuration("8s")
- client = &fasthttp.Client{
- ReadTimeout: readTimeout,
- WriteTimeout: writeTimeout,
- MaxIdleConnDuration: maxIdleConnDuration,
- MaxConnWaitTimeout: maxConnWaitTimeout,
- MaxIdemponentCallAttempts: 3,
- NoDefaultUserAgentHeader: true, // Don't send: User-Agent: fasthttp
- DisableHeaderNamesNormalizing: true, // If you set the case on your headers correctly you can enable this
- DisablePathNormalizing: true,
- }
- curProxy.UnSet = true
- lock = sync.RWMutex{} // 初始化读写锁
- log.Info("Http连接池初始化完毕...")
- }
- func SendGetRequest(url string, headers map[string]string) (*fasthttp.Response, error) {
- req := fasthttp.AcquireRequest()
- req.SetRequestURI(url)
- req.Header.SetMethod(fasthttp.MethodGet)
- for key, value := range headers {
- req.Header.Add(key, value)
- }
- resp := fasthttp.AcquireResponse()
- err := client.Do(req, resp)
- fasthttp.ReleaseRequest(req)
- if err == nil {
- return resp, nil
- } else {
- log.Warnf("发送Get请求失败,地址%s,错误%v", url, err)
- return resp, err
- }
- }
- func SendPostRequest(url string, headers map[string]string, body []byte) (*fasthttp.Response, error) {
- req := fasthttp.AcquireRequest()
- defer fasthttp.ReleaseRequest(req)
- req.SetRequestURI(url)
- req.Header.SetMethod(fasthttp.MethodPost)
- for key, value := range headers {
- req.Header.Add(key, value)
- }
- req.SetBody(body)
- resp := fasthttp.AcquireResponse()
- err := client.Do(req, resp)
- if err == nil {
- log.Debugf("请求地址 %s 成功", url)
- return resp, nil
- } else {
- log.Warnf("Post地址%s,错误%v", url, err)
- return resp, err
- }
- }
- func SendGetRequestAndFixHost(url string, host string, headers map[string]string) (*fasthttp.Response, error) {
- req := fasthttp.AcquireRequest()
- req.SetRequestURI(url)
- req.Header.SetMethod(fasthttp.MethodGet)
- for key, value := range headers {
- req.Header.Add(key, value)
- }
- resp := fasthttp.AcquireResponse()
- err := client.Do(req, resp)
- fasthttp.ReleaseRequest(req)
- if err == nil {
- return resp, nil
- } else {
- log.Warnf("发送Get请求失败,地址%s,错误%v", url, err)
- return resp, err
- }
- }
- func GetQueryUrl(url string, params map[string]string) string {
- if len(params) <= 0 {
- return url
- }
- paramsList := make([]string, 0)
- for key, value := range params {
- str := fmt.Sprintf("%s=%s", key, value)
- paramsList = append(paramsList, str)
- }
- paramsStr := strings.Join(paramsList, "&")
- return fmt.Sprintf("%s?%s", url, paramsStr)
- }
|