Reputation: 1
Below is the Go code:
var (
Address = os.Getenv("ADDR")
Token = os.Getenv("TOKEN")
)
It reads the environment variables in Windows.
On a Windows laptop, I have the privilege to set user variables for my user login only. I created two variables (for the above), but os.Getenv()
cannot read the values.
I do not have the privilege to set system variables.
How can I set environment variables in Windows, with my user login?
Upvotes: 1
Views: 13579
Reputation: 19
If you want to use some user-defined variable in Windows environment, I recommend the library godotenv
go get github.com/joho/godotenv
you can set your variable in the .env file in the same directory of the main. go. like
ADDR=127.0.0.1
TOKEN=localhost
In your go program, you can use these variable like:
package main
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
fmt.Println("ADDR: ", os.Getenv("ADDR"))
fmt.Println("TOKEN: ", os.Getenv("TOKEN"))
}
Upvotes: 1
Reputation: 20088
You can try using the set method in a terminal in the following way:
set NODE_HOME=C:\Users\359855\Downloads\node-v14.16.0-win-x64
set PATH=%PATH%;%NODE_HOME%;
Upvotes: 1
Reputation: 11
I don't know if this is the same as yours, but I use: os.environ.get('environment variable')
.
Also you can add a print(environment variable)
and run to check if everything is fine. Let's say the environment variable is SECRET_KEY
.
You add a print(SECRET_KEY)
to your line of code and run, check your terminal for possible results.
Upvotes: 0
Reputation: 1610
In Windows, environment variables can be applied in two ways.
Set
modifies the current shell's (the window's) environment values, and the change is available immediately, but it is temporary. The change will not affect other shells that are running, and as soon as you close the shell, the new value is lost until such time as you run set again.
cmd> SET ADDR=127.0.0.1
cmd> SET TOKEN=ABCD1234
cmd> SET
setx
modifies the value permanently, which affects all future shells, but does not modify the environment of the shells already running. You have to exit the shell and reopen it before the change will be available, but the value will remain modified until you change it again.
cmd> setx ADDR "127.0.0.1"
cmd> setx TOKEN "ABCD1234"
cmd> SET
Upvotes: 8