From 6790d76150ccbbf40cb7227f37f7c3400041415e Mon Sep 17 00:00:00 2001 From: licong Date: Tue, 15 Mar 2022 17:55:41 +0800 Subject: [PATCH] init --- .gitignore | 2 +- go.mod | 4 +++- go.sum | 2 ++ main.go | 23 ++++++++++++++++++----- 4 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 go.sum diff --git a/.gitignore b/.gitignore index 8696fc8..adb36c8 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -with-proxy.exe \ No newline at end of file +*.exe \ No newline at end of file diff --git a/go.mod b/go.mod index 8e3af82..aa20434 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ -module github.com/hellojukay/with-proxy +module github.com/hellojukay/with-env go 1.17 + +require github.com/joho/godotenv v1.4.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8c9f290 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= +github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= diff --git a/main.go b/main.go index 35cd29e..f051d5a 100644 --- a/main.go +++ b/main.go @@ -4,15 +4,28 @@ import ( "fmt" "os" "os/exec" + "path/filepath" + + "github.com/joho/godotenv" ) +// first load env from ~/.env +// second load env from .env +func init() { + home, _ := os.UserHomeDir() + loadEnv(filepath.Join(home, ".env"), ".env") +} + +func loadEnv(files ...string) { + for _, envfile := range files { + if _, err := os.Stat(envfile); !os.IsNotExist(err) { + _ = godotenv.Overload(envfile) + } + } + +} func main() { c := exec.Command(os.Args[1], os.Args[2:]...) - c.Env = append(c.Env, os.Environ()...) - c.Env = append(c.Env, "https_proxy=http://127.0.0.1:7890") - c.Env = append(c.Env, "http_proxy=http://127.0.0.1:7890") - c.Env = append(c.Env, "HTTPS_PROXY=http://127.0.0.1:7890") - c.Env = append(c.Env, "HTTP_PROXY=http://127.0.0.1:7890") c.Stderr = os.Stderr c.Stdout = os.Stdout if err := c.Run(); err != nil {