在我将环境变量写入 /etc/enviornment 文件之后,我已经尝试了我的 go 代码中的源命令。
下面是示例代码。
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
)
func main() {
address := "localhost:9090"
file, err := os.OpenFile("/etc/environment", os.O_RDWR, 0644)
defer file.Close()
if err != nil {
panic(err)
}
input, err := ioutil.ReadAll(file)
if err != nil {
log.Fatalln(err)
}
lines := strings.Split(string(input), "\n")
for i, line := range lines {
if strings.Contains(line, "HTTP_PROXY") {
lines[i] = "HTTP_PROXY=" + address
} else {
if i == (len(lines) - 1) {
lines[i] = "HTTP_PROXY=" + address
}
}
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile("/etc/environment", []byte(output), 0644)
if err != nil {
log.Fatalln(err)
}
cmd := exec.Command("bash", "-c", "source /etc/environment")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
fmt.Println("cmd=================>", cmd, err)
if err != nil {
fmt.Println(err)
}
}
它返回任何错误
但是当我尝试在使用中检查我的 HTTP_PROXY 时,env | grep -i proxy我没有看到它得到反映。我只能在重新启动系统或从另一个终端再次运行 source 命令时才能看到更改已完成。
我想要的只是在不重新启动系统的情况下从 go 代码更改 os 代理。
如果有任何其他方法,请同时提及。
明月笑刀无情
侃侃尔雅
杨魅力
随时随地看视频慕课网APP
相关分类