I am working on a set of projects that use .env files for configuration, where each .env file exports a number of environment variables. The files are setup like;
export VARIABLE1=foo
I use the Windows Linux subsystem a lot for this, but would like to also be able to run these projects on my windows machine. The projects in question are Golang.
IS there any easy way to programatically set Windows environment variables (preferably termporarily) from these .env files? These is mostly so I can debug within VSCode.
import "os" func Clearenv() func Environ() []string func Expand(s string, mapping func(string) string) string func ExpandEnv(s string) string func Getenv(key string) string func Setenv(key, value string) error func Unsetenv(key string) error
Read the env file lines using bufio.Scanner
. Parse the lines using the strings
package. Use the os
package environment variable functions.
For example,
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strings"
)
func parseLine(line string) (key, value string) {
line = strings.TrimSpace(line)
const export = `export `
if !strings.HasPrefix(line, export) {
return "", ""
}
line = strings.TrimPrefix(line, export)
fields := strings.SplitN(line, "=", 2)
if len(fields) > 0 {
key = strings.TrimSpace(fields[0])
if len(fields) > 1 {
value = strings.TrimSpace(fields[1])
}
}
return key, value
}
func setenv(r io.Reader) error {
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
key, value := parseLine(line)
if len(key) < 1 {
continue
}
err := os.Setenv(key, value)
if err != nil {
return err
}
}
if err := s.Err(); err != nil {
return err
}
return nil
}
func main() {
envFile := bytes.NewBufferString(
"export VARIABLE1=foo
export VARIABLE2=bar
",
)
err := setenv(envFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
for _, key := range []string{`VARIABLE1`, `VARIABLE2`} {
env, found := os.LookupEnv(key)
fmt.Println(key, found, env)
}
}
Playground: https://play.golang.org/p/pZKQ0GW5eCu
Output:
VARIABLE1 true foo
VARIABLE2 true bar
i used godotenv library.
Add configuration values to a .env file at the root of project:
PORT=8080
NAME=FlowAPI
main.go
package main
import (
"log"
"github.com/joho/godotenv"
"fmt"
"os"
)
func init() {
// loads values from .env into the system
if err := godotenv.Load(); err != nil {
log.Print("No .env file found")
}
}
func main() {
// Get the PORT environment variable
port, exists := os.LookupEnv("PORT")
if exists {
fmt.Println(port)
}
}