• 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	"fmt"
20	"github.com/sirupsen/logrus"
21	"net/http"
22	"net/url"
23	"strings"
24	"sync"
25	"time"
26)
27
28type ProxyConfig struct {
29	ServerList string `key:"server_list" default:""`
30	User       string `key:"user" default:""`
31	Password   string `key:"password" default:""`
32}
33
34var proxyClient = http.DefaultClient
35var (
36	proxyUser     string
37	proxyPassword string
38	proxyList     []string
39	proxyIndex    int
40	proxyLock     sync.Mutex
41)
42
43func init() {
44	var config ProxyConfig
45	ParseFromConfigFile("proxy", &config)
46	if len(config.ServerList) != 0 {
47		proxyList = strings.Split(config.ServerList, ",")
48	}
49	proxyUser = config.User
50	proxyPassword = config.Password
51	proxyIndex = len(proxyList)
52	SwitchProxy()
53	t := time.NewTicker(6 * time.Hour)
54	go func() {
55		<-t.C
56		proxyLock.Lock()
57		proxyIndex = len(proxyList)
58		proxyLock.Unlock()
59	}()
60}
61
62func SwitchProxy() {
63	if len(proxyList) == 0 {
64		return
65	}
66	proxyLock.Lock()
67	defer proxyLock.Unlock()
68	proxyIndex++
69	if proxyIndex >= len(proxyList) {
70		proxyIndex = 0
71	}
72	var proxyURL *url.URL
73	var err error
74	logrus.Infof("switching proxy to %s", proxyList[proxyIndex])
75	if proxyUser == "" {
76		proxyURL, err = url.Parse(fmt.Sprintf("http://%s", proxyList[proxyIndex]))
77	} else {
78		proxyURL, err = url.Parse(fmt.Sprintf("http://%s:%s@%s", proxyUser, url.QueryEscape(proxyPassword), proxyList[proxyIndex]))
79	}
80	if err != nil {
81		logrus.Errorf("failed to parse proxy url, err: %v", err)
82	}
83	proxyClient = &http.Client{
84		Transport: &http.Transport{
85			Proxy: http.ProxyURL(proxyURL),
86		},
87	}
88}
89