• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16package utils
17
18import (
19	"bytes"
20	"fmt"
21	"github.com/sirupsen/logrus"
22	"io"
23	"net/http"
24	"time"
25)
26
27func DoSimpleHttpReqRaw(method string, url string, body []byte, header map[string]string) (response *http.Response, err error) {
28	maxRetry := len(proxyList)
29	if maxRetry < 3 {
30		maxRetry = 3
31	}
32	for i := 0; i < maxRetry; i++ {
33		if response, err = doSimpleHttpReqImpl(method, url, body, header); err == nil {
34			return
35		}
36		time.Sleep(time.Second)
37	}
38	return
39}
40
41func DoSimpleHttpReq(method string, url string, body []byte, header map[string]string) (ret []byte, err error) {
42	var resp *http.Response
43	maxRetry := len(proxyList)
44	if maxRetry < 3 {
45		maxRetry = 3
46	}
47	for i := 0; i < maxRetry; i++ {
48		if resp, err = doSimpleHttpReqImpl(method, url, body, header); err == nil {
49			ret, err = io.ReadAll(resp.Body)
50			resp.Body.Close()
51			return
52		}
53		time.Sleep(time.Second)
54	}
55	return
56}
57
58func doSimpleHttpReqImpl(method string, url string, body []byte, header map[string]string) (response *http.Response, err error) {
59	logrus.Infof("%s %s", method, url)
60	req, err := http.NewRequest(method, url, bytes.NewReader(body))
61	if err != nil {
62		return nil, err
63	}
64	for k, v := range header {
65		req.Header.Set(k, v)
66	}
67	resp, err := proxyClient.Do(req)
68	if err != nil {
69		return nil, err
70	}
71	if resp.StatusCode >= 300 {
72		defer resp.Body.Close()
73		data, _ := io.ReadAll(resp.Body)
74		if resp.StatusCode == http.StatusProxyAuthRequired || resp.StatusCode == http.StatusForbidden {
75			SwitchProxy()
76		}
77		logrus.Errorf("%s %s: code: %d body: %s", method, url, resp.StatusCode, string(data))
78		return nil, fmt.Errorf("%s %s: code: %d body: %s", method, url, resp.StatusCode, string(data))
79	}
80	return resp, nil
81}
82