You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

proxy.go 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2023 The casbin Authors. All Rights Reserved.
  2. //
  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. package proxy
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "net"
  19. "net/http"
  20. "strings"
  21. "time"
  22. "github.com/casibase/casibase/conf"
  23. "golang.org/x/net/proxy"
  24. )
  25. var (
  26. DefaultHttpClient *http.Client
  27. ProxyHttpClient *http.Client
  28. )
  29. func InitHttpClient() {
  30. // not use proxy
  31. DefaultHttpClient = http.DefaultClient
  32. // use proxy
  33. ProxyHttpClient = getProxyHttpClient()
  34. }
  35. func isAddressOpen(address string) bool {
  36. timeout := time.Millisecond * 100
  37. conn, err := net.DialTimeout("tcp", address, timeout)
  38. if err != nil {
  39. // cannot connect to address, proxy is not active
  40. return false
  41. }
  42. if conn != nil {
  43. defer conn.Close()
  44. fmt.Printf("Socks5 proxy enabled: %s\n", address)
  45. return true
  46. }
  47. return false
  48. }
  49. func getProxyHttpClient() *http.Client {
  50. socks5Proxy := conf.GetConfigString("socks5Proxy")
  51. if socks5Proxy == "" {
  52. return &http.Client{}
  53. }
  54. if !isAddressOpen(socks5Proxy) {
  55. return &http.Client{}
  56. }
  57. // https://stackoverflow.com/questions/33585587/creating-a-go-socks5-client
  58. dialer, err := proxy.SOCKS5("tcp", socks5Proxy, nil, proxy.Direct)
  59. if err != nil {
  60. panic(err)
  61. }
  62. tr := &http.Transport{Dial: dialer.Dial, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
  63. return &http.Client{
  64. Transport: tr,
  65. }
  66. }
  67. func GetHttpClient(url string) *http.Client {
  68. if strings.Contains(url, "githubusercontent.com") || strings.Contains(url, "googleusercontent.com") {
  69. return ProxyHttpClient
  70. } else {
  71. return DefaultHttpClient
  72. }
  73. }