-
Notifications
You must be signed in to change notification settings - Fork 25
/
proxy.go
72 lines (59 loc) · 1.81 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package http
import (
"os"
"strings"
"go.uber.org/fx"
"github.com/fluxninja/aperture/v2/pkg/config"
"github.com/fluxninja/aperture/v2/pkg/log"
)
const (
defaultProxyKey = "client.proxy"
)
// ProxyModule returns the fx module that applies the provided proxy configuration.
func ProxyModule() fx.Option {
return fx.Options(
fx.Invoke(ProxyConstructor{}.applyProxyConfig),
)
}
// ProxyConstructor holds fields used to configure Proxy.
type ProxyConstructor struct {
ConfigKey string
DefaultConfig ProxyConfig
}
// ProxyConfig holds proxy configuration.
// This configuration has preference over environment variables HTTP_PROXY, HTTPS_PROXY or NO_PROXY. See <https://pkg.go.dev/golang.org/x/net/http/httpproxy#Config>
// swagger:model
// +kubebuilder:object:generate=true
type ProxyConfig struct {
HTTPProxy string `json:"http" validate:"omitempty,url|hostname_port"`
HTTPSProxy string `json:"https" validate:"omitempty,url|hostname_port"`
NoProxy []string `json:"no_proxy,omitempty" validate:"omitempty,dive,ip|cidr|fqdn|hostname_port"`
}
func (constructor ProxyConstructor) applyProxyConfig(unmarshaller config.Unmarshaller) error {
if constructor.ConfigKey == "" {
constructor.ConfigKey = defaultProxyKey
}
var err error
config := constructor.DefaultConfig
if err = unmarshaller.UnmarshalKey(constructor.ConfigKey, &config); err != nil {
log.Error().Err(err).Msg("Unable to deserialize client proxy configuration!")
return err
}
if config.HTTPProxy != "" ||
config.HTTPSProxy != "" ||
len(config.NoProxy) > 0 {
err = os.Setenv("HTTP_PROXY", config.HTTPProxy)
if err != nil {
return err
}
err = os.Setenv("HTTPS_PROXY", config.HTTPSProxy)
if err != nil {
return err
}
err = os.Setenv("NO_PROXY", strings.Join(config.NoProxy, ","))
if err != nil {
return err
}
}
return nil
}