github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/proxy/proxy.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package proxy
     7  
     8  import (
     9  	"net/http"
    10  	"net/url"
    11  	"os"
    12  	"sync"
    13  
    14  	"github.com/gitbundle/modules/log"
    15  	"github.com/gitbundle/modules/setting"
    16  
    17  	"github.com/gobwas/glob"
    18  )
    19  
    20  var (
    21  	once         sync.Once
    22  	hostMatchers []glob.Glob
    23  )
    24  
    25  // GetProxyURL returns proxy url
    26  func GetProxyURL() string {
    27  	if !setting.Proxy.Enabled {
    28  		return ""
    29  	}
    30  
    31  	if setting.Proxy.ProxyURL == "" {
    32  		if os.Getenv("http_proxy") != "" {
    33  			return os.Getenv("http_proxy")
    34  		}
    35  		return os.Getenv("https_proxy")
    36  	}
    37  	return setting.Proxy.ProxyURL
    38  }
    39  
    40  // Match return true if url needs to be proxied
    41  func Match(u string) bool {
    42  	if !setting.Proxy.Enabled {
    43  		return false
    44  	}
    45  
    46  	// enforce do once
    47  	Proxy()
    48  
    49  	for _, v := range hostMatchers {
    50  		if v.Match(u) {
    51  			return true
    52  		}
    53  	}
    54  	return false
    55  }
    56  
    57  // Proxy returns the system proxy
    58  func Proxy() func(req *http.Request) (*url.URL, error) {
    59  	if !setting.Proxy.Enabled {
    60  		return func(req *http.Request) (*url.URL, error) {
    61  			return nil, nil
    62  		}
    63  	}
    64  	if setting.Proxy.ProxyURL == "" {
    65  		return http.ProxyFromEnvironment
    66  	}
    67  
    68  	once.Do(func() {
    69  		for _, h := range setting.Proxy.ProxyHosts {
    70  			if g, err := glob.Compile(h); err == nil {
    71  				hostMatchers = append(hostMatchers, g)
    72  			} else {
    73  				log.Error("glob.Compile %s failed: %v", h, err)
    74  			}
    75  		}
    76  	})
    77  
    78  	return func(req *http.Request) (*url.URL, error) {
    79  		for _, v := range hostMatchers {
    80  			if v.Match(req.URL.Host) {
    81  				return http.ProxyURL(setting.Proxy.ProxyURLFixed)(req)
    82  			}
    83  		}
    84  		return http.ProxyFromEnvironment(req)
    85  	}
    86  }