casdoor/proxy/proxy.go

85 lines
1.9 KiB
Go
Raw Normal View History

2022-02-13 23:39:27 +08:00
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
2021-08-21 22:16:25 +08:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package proxy
import (
2021-09-21 18:14:00 +08:00
"fmt"
"net"
2021-08-21 22:16:25 +08:00
"net/http"
2021-08-21 23:17:33 +08:00
"strings"
2021-09-21 18:14:00 +08:00
"time"
2021-08-21 22:16:25 +08:00
"github.com/astaxie/beego"
"golang.org/x/net/proxy"
)
var DefaultHttpClient *http.Client
var ProxyHttpClient *http.Client
func InitHttpClient() {
// not use proxy
DefaultHttpClient = http.DefaultClient
// use proxy
2021-09-21 18:14:00 +08:00
ProxyHttpClient = getProxyHttpClient()
}
func isAddressOpen(address string) bool {
timeout := time.Millisecond * 100
conn, err := net.DialTimeout("tcp", address, timeout)
if err != nil {
// cannot connect to address, proxy is not active
return false
}
if conn != nil {
defer conn.Close()
fmt.Printf("Socks5 proxy enabled: %s\n", address)
return true
}
return false
}
func getProxyHttpClient() *http.Client {
2022-03-03 08:59:38 +08:00
sock5Proxy := beego.AppConfig.String("sock5Proxy")
if sock5Proxy == "" {
2021-09-21 18:14:00 +08:00
return &http.Client{}
}
2022-03-03 08:59:38 +08:00
if !isAddressOpen(sock5Proxy) {
2021-09-21 18:14:00 +08:00
return &http.Client{}
2021-08-21 22:16:25 +08:00
}
// https://stackoverflow.com/questions/33585587/creating-a-go-socks5-client
2022-03-03 08:59:38 +08:00
dialer, err := proxy.SOCKS5("tcp", sock5Proxy, nil, proxy.Direct)
2021-08-21 22:16:25 +08:00
if err != nil {
panic(err)
}
tr := &http.Transport{Dial: dialer.Dial}
2021-09-21 18:14:00 +08:00
return &http.Client{
2021-08-21 22:16:25 +08:00
Transport: tr,
}
}
2021-08-21 23:17:33 +08:00
func GetHttpClient(url string) *http.Client {
if strings.Contains(url, "githubusercontent.com") {
return ProxyHttpClient
} else {
return DefaultHttpClient
}
}