2021-06-24 12:21:03 +00:00
|
|
|
package envproxy
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type EnvProxy struct {
|
2021-06-29 14:47:42 +00:00
|
|
|
fromPrefix string
|
|
|
|
toPrefix string
|
|
|
|
defaultEnv map[string]string
|
2021-06-24 12:21:03 +00:00
|
|
|
}
|
|
|
|
|
2021-07-01 15:47:03 +00:00
|
|
|
func NewEnvProxy(fromPrefix, toPrefix string) *EnvProxy {
|
2021-06-24 12:21:03 +00:00
|
|
|
envMap := map[string]string{}
|
|
|
|
for _, variable := range os.Environ() {
|
|
|
|
tmp := strings.SplitN(variable, "=", 2)
|
|
|
|
envMap[tmp[0]] = tmp[1]
|
|
|
|
}
|
|
|
|
return &EnvProxy{
|
2021-07-01 15:47:03 +00:00
|
|
|
fromPrefix: fromPrefix,
|
|
|
|
toPrefix: toPrefix,
|
2021-06-29 14:47:42 +00:00
|
|
|
defaultEnv: envMap,
|
2021-06-24 12:21:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *EnvProxy) Apply() {
|
2021-06-29 14:47:42 +00:00
|
|
|
if s.fromPrefix == "" || s.toPrefix == "" {
|
2021-06-24 12:21:03 +00:00
|
|
|
return
|
|
|
|
}
|
2021-06-29 14:47:42 +00:00
|
|
|
for key, value := range s.defaultEnv {
|
|
|
|
if strings.HasPrefix(key, s.fromPrefix) {
|
|
|
|
key = strings.Replace(key, s.fromPrefix, s.toPrefix, 1)
|
2021-06-24 12:21:03 +00:00
|
|
|
os.Setenv(key, value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *EnvProxy) Restore() {
|
2021-06-29 14:47:42 +00:00
|
|
|
if s.fromPrefix == "" || s.toPrefix == "" {
|
2021-06-24 12:21:03 +00:00
|
|
|
return
|
|
|
|
}
|
2021-06-29 14:47:42 +00:00
|
|
|
for key, value := range s.defaultEnv {
|
|
|
|
if strings.HasPrefix(key, s.fromPrefix) {
|
|
|
|
key = strings.Replace(key, s.fromPrefix, s.toPrefix, 1)
|
|
|
|
value = s.defaultEnv[key]
|
2021-06-24 12:21:03 +00:00
|
|
|
}
|
|
|
|
os.Setenv(key, value)
|
|
|
|
}
|
|
|
|
}
|