casdoor/proxy/proxy.go

87 lines
2.0 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/casdoor/casdoor/conf"
2021-08-21 22:16:25 +08:00
"golang.org/x/net/proxy"
)
var (
DefaultHttpClient *http.Client
ProxyHttpClient *http.Client
)
2021-08-21 22:16:25 +08:00
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-07-08 23:24:54 +08:00
socks5Proxy := conf.GetConfigString("socks5Proxy")
if socks5Proxy == "" {
2021-09-21 18:14:00 +08:00
return &http.Client{}
}
2022-07-08 23:24:54 +08:00
if !isAddressOpen(socks5Proxy) {
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-07-08 23:24:54 +08:00
dialer, err := proxy.SOCKS5("tcp", socks5Proxy, 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 {
2022-06-29 22:01:38 +08:00
if strings.Contains(url, "githubusercontent.com") || strings.Contains(url, "googleusercontent.com") {
2021-08-21 23:17:33 +08:00
return ProxyHttpClient
} else {
return DefaultHttpClient
}
}