http.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package lxhttp
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "crypto/tls"
  6. "encoding/base64"
  7. "encoding/json"
  8. "git.listensoft.net/tool/jspkit/logger"
  9. "go.uber.org/zap"
  10. "io"
  11. "net/http"
  12. "net/http/cookiejar"
  13. "net/url"
  14. "strings"
  15. "time"
  16. "git.listensoft.net/tool/jspkit/taxerr"
  17. "golang.org/x/net/publicsuffix"
  18. )
  19. // POSTForm 发送Form表单请求
  20. func POSTForm(c *http.Client, requrl string, params map[string]string, headers map[string]string) ([]byte, error) {
  21. form := url.Values{}
  22. for k, v := range params {
  23. form.Add(k, v)
  24. }
  25. var bys []byte
  26. req, err := http.NewRequest("POST", requrl, strings.NewReader(form.Encode()))
  27. if err != nil {
  28. return bys, err
  29. }
  30. for k, v := range headers {
  31. req.Header.Add(k, v)
  32. }
  33. resp, err := c.Do(req)
  34. if err != nil {
  35. return bys, err
  36. }
  37. defer resp.Body.Close()
  38. return io.ReadAll(resp.Body)
  39. }
  40. // GET 发送get请求
  41. func GET(c *http.Client, requrl string, params map[string]string, headers map[string]string) ([]byte, error) {
  42. form := url.Values{}
  43. for k, v := range params {
  44. form.Add(k, v)
  45. }
  46. var bys []byte
  47. req, err := http.NewRequest("GET", requrl, strings.NewReader(form.Encode()))
  48. if err != nil {
  49. return bys, err
  50. }
  51. for k, v := range headers {
  52. req.Header.Add(k, v)
  53. }
  54. resp, err := c.Do(req)
  55. if err != nil {
  56. return bys, err
  57. }
  58. defer resp.Body.Close()
  59. return io.ReadAll(resp.Body)
  60. }
  61. func GZIPDecode(in []byte) ([]byte, error) {
  62. reader, err := gzip.NewReader(bytes.NewReader(in))
  63. if err != nil {
  64. var out []byte
  65. return out, err
  66. }
  67. defer reader.Close()
  68. return io.ReadAll(reader)
  69. }
  70. // POSTJson 发送json请求
  71. func POSTJson1(c *http.Client, requrl string, params map[string]any, headers map[string]string) ([]byte, error) {
  72. bytesData, _ := json.Marshal(params)
  73. request, err := http.NewRequest("POST", requrl, bytes.NewReader(bytesData))
  74. if err != nil {
  75. return nil, err
  76. }
  77. for k, v := range headers {
  78. request.Header.Add(k, v)
  79. }
  80. request.Header.Set("Content-Type", "application/json;charset=UTF-8")
  81. request.Header.Set("Accept-Encoding", "gzip, deflate, br")
  82. resp, err := c.Do(request)
  83. if err != nil {
  84. return nil, err
  85. }
  86. defer resp.Body.Close()
  87. bytes, err := io.ReadAll(resp.Body)
  88. if err != nil {
  89. return nil, err
  90. }
  91. if strings.Contains(resp.Header.Get(`Content-Encoding`), "gzip") {
  92. return GZIPDecode(bytes)
  93. }
  94. return bytes, nil
  95. }
  96. // POSTJson 发送json请求
  97. func POSTJsonAny(c *http.Client, requrl string, params any, headers map[string]string) ([]byte, error) {
  98. bytesData, _ := json.Marshal(params)
  99. request, err := http.NewRequest("POST", requrl, bytes.NewReader(bytesData))
  100. if err != nil {
  101. return nil, err
  102. }
  103. for k, v := range headers {
  104. request.Header.Add(k, v)
  105. }
  106. request.Header.Set("Content-Type", "application/json;charset=UTF-8")
  107. request.Header.Set("Accept-Encoding", "gzip, deflate, br")
  108. resp, err := c.Do(request)
  109. if err != nil {
  110. return nil, err
  111. }
  112. defer resp.Body.Close()
  113. bytes, err := io.ReadAll(resp.Body)
  114. if err != nil {
  115. return nil, err
  116. }
  117. if strings.Contains(resp.Header.Get(`Content-Encoding`), "gzip") {
  118. return GZIPDecode(bytes)
  119. }
  120. return bytes, nil
  121. }
  122. // POSTJson 发送json请求
  123. func POSTStrReader(c *http.Client, requrl, params string, headers map[string]string) ([]byte, error) {
  124. request, err := http.NewRequest("POST", requrl, strings.NewReader(params))
  125. if err != nil {
  126. return nil, err
  127. }
  128. for k, v := range headers {
  129. request.Header.Add(k, v)
  130. }
  131. request.Header.Set("Accept-Encoding", "gzip, deflate, br")
  132. resp, err := c.Do(request)
  133. if err != nil {
  134. return nil, err
  135. }
  136. defer resp.Body.Close()
  137. bytes, err := io.ReadAll(resp.Body)
  138. if err != nil {
  139. return nil, err
  140. }
  141. if strings.Contains(resp.Header.Get(`Content-Encoding`), "gzip") {
  142. return GZIPDecode(bytes)
  143. }
  144. return bytes, nil
  145. }
  146. // POSTJson 发送json请求
  147. func POSTJson(c *http.Client, requrl string, params map[string]string, headers map[string]string) ([]byte, error) {
  148. bytesData, _ := json.Marshal(params)
  149. request, err := http.NewRequest("POST", requrl, bytes.NewReader(bytesData))
  150. if err != nil {
  151. return nil, err
  152. }
  153. for k, v := range headers {
  154. request.Header.Add(k, v)
  155. }
  156. request.Header.Set("Content-Type", "application/json;charset=UTF-8")
  157. request.Header.Set("Accept-Encoding", "gzip, deflate, br")
  158. resp, err := c.Do(request)
  159. if err != nil {
  160. return nil, err
  161. }
  162. if resp.StatusCode == 504 && strings.Contains(requrl, "keepalive") { // 超时
  163. return nil, taxerr.KeepTimeOut
  164. }
  165. defer resp.Body.Close()
  166. bytes, err := io.ReadAll(resp.Body)
  167. if err != nil {
  168. return nil, err
  169. }
  170. if strings.Contains(resp.Header.Get(`Content-Encoding`), "gzip") {
  171. return GZIPDecode(bytes)
  172. }
  173. return bytes, nil
  174. }
  175. // Get http get请求
  176. func Get(c *http.Client, url string) ([]byte, error) {
  177. resp, err := c.Get(url)
  178. if err != nil {
  179. return nil, err
  180. }
  181. defer resp.Body.Close()
  182. return io.ReadAll(resp.Body)
  183. }
  184. // 发出Post请求 请求数据和返回数据都是json格式
  185. func PostJson(url string, data map[string]interface{}, v any) error {
  186. bytesData, _ := json.Marshal(data)
  187. request, err := http.NewRequest("POST", url, bytes.NewReader(bytesData))
  188. if err != nil {
  189. logger.GetLogger().Info("err", zap.Error(err))
  190. return err
  191. }
  192. request.Header.Set("Content-Type", "application/json;charset=UTF-8")
  193. client := NewHttpClient()
  194. resp, err := client.Do(request)
  195. if err != nil {
  196. return err
  197. }
  198. defer resp.Body.Close()
  199. body, err := io.ReadAll(resp.Body)
  200. if err != nil {
  201. return err
  202. }
  203. if err = json.Unmarshal(body, v); err != nil {
  204. return err
  205. }
  206. return nil
  207. }
  208. // NewHttpClient 生成一个htppclient
  209. func NewHttpClient(tt ...int) *http.Client {
  210. if len(tt) == 0 {
  211. tt = append(tt, 60)
  212. }
  213. tr := &http.Transport{
  214. // Proxy: http.ProxyFromEnvironment, // 从环境变量中获取代理
  215. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 忽略证书校验错误
  216. }
  217. var c = &http.Client{
  218. Timeout: time.Duration(tt[0]) * time.Second,
  219. Transport: tr,
  220. }
  221. options := cookiejar.Options{
  222. PublicSuffixList: publicsuffix.List,
  223. }
  224. curCookieJar, _ := cookiejar.New(&options)
  225. c.Jar = curCookieJar
  226. return c
  227. }
  228. // NewHttpClient 生成一个htppclient 请求等待时间加长
  229. func NewLongHttpClient() *http.Client {
  230. tr := &http.Transport{
  231. // Proxy: http.ProxyFromEnvironment, // 从环境变量中获取代理
  232. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 忽略证书校验错误
  233. }
  234. var c = &http.Client{
  235. Timeout: time.Duration(600 * time.Second),
  236. Transport: tr,
  237. }
  238. options := cookiejar.Options{
  239. PublicSuffixList: publicsuffix.List,
  240. }
  241. curCookieJar, _ := cookiejar.New(&options)
  242. c.Jar = curCookieJar
  243. return c
  244. }
  245. // NewHttpClient 生成一个代理htppclient
  246. func NewHttpClientForProxy(proxy string) *http.Client {
  247. var tr *http.Transport
  248. if proxy == "" {
  249. tr = &http.Transport{
  250. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //忽略证书校验
  251. }
  252. } else {
  253. p, _ := url.Parse(proxy)
  254. tr = &http.Transport{
  255. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //忽略证书校验
  256. Proxy: http.ProxyURL(p),
  257. }
  258. }
  259. var c = &http.Client{
  260. Timeout: time.Duration(20 * time.Second),
  261. Transport: tr,
  262. }
  263. options := cookiejar.Options{
  264. PublicSuffixList: publicsuffix.List,
  265. }
  266. curCookieJar, _ := cookiejar.New(&options)
  267. c.Jar = curCookieJar
  268. return c
  269. }
  270. // NewHttpClient 生成一个待认证的htppclient (仅适用西藏)
  271. func NewHttpClientForXizang(ip, auth string) *http.Client {
  272. p, _ := url.Parse(ip)
  273. tr := &http.Transport{
  274. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //忽略证书校验
  275. Proxy: http.ProxyURL(p),
  276. }
  277. if auth != "" {
  278. tr.ProxyConnectHeader = http.Header{
  279. "Proxy-Authorization": []string{"Basic " + base64.StdEncoding.EncodeToString([]byte(auth))},
  280. }
  281. }
  282. var c = &http.Client{
  283. Timeout: time.Duration(20 * time.Second),
  284. Transport: tr,
  285. }
  286. options := cookiejar.Options{
  287. PublicSuffixList: publicsuffix.List,
  288. }
  289. curCookieJar, _ := cookiejar.New(&options)
  290. c.Jar = curCookieJar
  291. return c
  292. }
  293. // NewHttpClientForLocalProxy 针对本地代理 需要账号认证的 不认证的也可以用,后面全用这个
  294. func NewHttpClientForLocalProxy(ip, auth string) *http.Client {
  295. if ip == "" {
  296. return NewHttpClient()
  297. }
  298. p, _ := url.Parse(ip)
  299. tr := &http.Transport{
  300. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //忽略证书校验
  301. Proxy: http.ProxyURL(p),
  302. }
  303. if auth != "" {
  304. tr.ProxyConnectHeader = http.Header{
  305. "Proxy-Authorization": []string{"Basic " + base64.StdEncoding.EncodeToString([]byte(auth))},
  306. }
  307. }
  308. var c = &http.Client{
  309. Timeout: time.Duration(60 * time.Second),
  310. Transport: tr,
  311. }
  312. options := cookiejar.Options{
  313. PublicSuffixList: publicsuffix.List,
  314. }
  315. curCookieJar, _ := cookiejar.New(&options)
  316. c.Jar = curCookieJar
  317. return c
  318. }
  319. // CreateFormReader 将 map 转换成 header
  320. func CreateFormReader(data map[string]string) io.Reader {
  321. form := url.Values{}
  322. for k, v := range data {
  323. form.Add(k, v)
  324. }
  325. return strings.NewReader(form.Encode())
  326. }
  327. func HttpClientPost(client *http.Client, URL, contentType string, body io.Reader) (res []byte, err error) {
  328. resp, err := client.Post(URL, contentType, body)
  329. if err != nil {
  330. return
  331. }
  332. defer resp.Body.Close()
  333. return io.ReadAll(resp.Body)
  334. }