Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables that last

I'm trying to set some environment variables on my machine using Go OS

    err := os.Setenv("DBHOST", dbHostLocal)
    if err != nil {
        log.Fatalf("err %v", err)
    }

It seems the variable is available to the Go program but once I quite / terminate the Go process the variable is no longer available. I'm wondering if it's possible to set these variables permanently. The reason is that i was looking to create a "setup" file with config files ( db name etc ) for the local and dev environment so that I could switch between without any setup at all... just one time go run setup.go.

like image 741
hey Avatar asked Jul 24 '14 16:07

hey


2 Answers

Whilst not considered possible, if you're building some cli tool that exits you could consider outputting the equivalent shell to STDOUT like: docker-machine eval.

Quick and dirty example:

package main

import (
  "fmt"
  "reflect"
  "strings"
)

type config struct {
  db_host string
  db_port int
  db_user string
}

func main() {
  c := config{"db.example.com", 3306, "user1"}

  ct := reflect.ValueOf(&c).Elem()
  typeOfC := ct.Type()

  for i := 0; i < ct.NumField(); i++ {
    f := ct.Field(i)
    fmt.Printf("%s=%v\n", strings.ToUpper(typeOfC.Field(i).Name), f)
  }
}

Output:
$ go run env.go
DB_HOST=db.example.com
DB_PORT=3306
DB_USER=user1

You can then eval it on the command line and have access to those variables.

$ eval $(go run env.go)
$ echo $DB_HOST
db.example.com
like image 141
Tim Birkett Avatar answered Oct 18 '22 23:10

Tim Birkett


Short: It is not possible. You can't change the environment of your parent process. You can only change your own and pass it to your children.

What you should do is maintain a config file. There are plenty of go config libs out there: ini, yaml, etc.

If your program changes the config, save it to disk after each change or one in a while or when the process exits.

like image 36
creack Avatar answered Oct 19 '22 00:10

creack