Os.Getenv ("") in go, cannot get custom environment variable

problem description

os.Getenv ("GOPATH") cannot be obtained, but os.Getenv ("HOME") can get

normally.

the environmental background of the problems and what methods you have tried

in the terminal, ech $GOPATH output normally, GOPATH variable is written in ~ / .bashrc file, os.Getenv ("GOPATH") cannot get
then try to write GOPATH variable in ~ / .profile, / etc/profile, / etc/environment, neither
os.Getenv (""), HOME, PATH can output normally, but custom GOPATH and GOROOT are not allowed

.

related codes

main.go:

package main

import (
    "os"
)

func main() {
    println(os.Getenv("HOME"))
    println(os.Getenv("GOPATH"))
}

Terminal:

zll@loong:~$ echo $GOPATH
/home/zll/go
zll@loong:~/temp$ go run main.go 
/home/zll

zll@loong:~/temp$ 

platform version in which the problem occurs

Ubuntu18.04
go 1.11.2

additional associations

when you use go"s third-party tool viper to parse environment variables, you can only get PATH and HOME system variables, but you can"t customize them.

package main

import (
    "fmt"

    "github.com/spf13/viper"
)

func main() {
    viper.AutomaticEnv()
    if env := viper.Get("GOPATH"); env == nil {
        println("error!")
    } else {
        fmt.Printf("%-sharpv\n", env)
    }
}

result:

error!

I wonder if there is a connection between them. Find the solution

Jan.01,2022

is related to the environment you are editing. You can get


if you open go mod
delete the go.mod go.sum in your project


finally find out what the problem is!
the environment variables written in .bashrc do not use the export command! In the implementation of main.go, sub-shell, that is definitely not available! I was trying to save trouble.

solution:

In the

.bashrc file, add export before setting the environment variable statement.
in addition, viper, is found in uppercase, and cannot be found if there is lowercase in the environment variable!

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b41c80-2c5d2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b41c80-2c5d2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?