How to set environment variables that last

前端 未结 4 1779
甜味超标
甜味超标 2020-12-11 04:48

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

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


        
相关标签:
4条回答
  • 2020-12-11 05:20

    It's possible if you write a value to the registry, but for this, your application needs administrator rights

    func setEnvironment(key string, value string){
       k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\ControlSet001\Control\Session Manager\Environment`, registry.ALL_ACCESS)
       if err != nil {
           log.Fatal(err)
       }
       defer k.Close()
    
       err = k.SetStringValue(key, value)
       if err != nil {
           log.Fatal(err)
       }
    }
    
    0 讨论(0)
  • 2020-12-11 05:22

    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.

    0 讨论(0)
  • 2020-12-11 05:36

    The only way to get the behavior you want is to alter the environment of the current shell, and the easiest way is with a simple shell script

    # setup.sh
    export DBHOST="dbhost.url"
    export CONFIG_VAR_TWO="testing"
    

    and then

    $ source setup.sh
    
    0 讨论(0)
  • 2020-12-11 05:40

    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
    
    0 讨论(0)
提交回复
热议问题