How to specify a windows file path in a Go application?
I am trying to specify the windows location for the .kube/config file for the Go client application without specifying the absolute path.
kubeconfig := flag.String("kubeconfig", "%USERPROFILE%/.kube/config", "location to the Kube config file")
Output :
panic: runtime error: invalid memory address or nil pointer dereference
When I use echo %USERPROFILE%
in a cmd, the output is C:\Users\<username>
, so I thought that 开发者_StackOverflow中文版this is because the different usage of \
and /
in the code and path.
I tried to specify the path using \
instead of /
but it gives out a syntax error.
Can anyone suggest me with a solution to use windows environmental variables to specify paths in a Go application? Thanks in advance.
The output of flag.String
itself does not expand environment variables but you can use os.ExpandEnv
to do that. However os.ExpandEnv
requires you to use the Unix notation for environment variables, i.e. $USERPROFILE
or ${USERPROFILE}
. You can get a clean file path for our specific OS (Windows in your case) using filepath.Clean
.
Example:
kubeconfig := flag.String("kubeconfig", "$USERPROFILE/.kube/config", "location to the Kube config file")
fmt.Println(*kubeconfig)
fmt.Println(os.ExpandEnv(*kubeconfig))
fmt.Println(filepath.Clean(os.ExpandEnv(*kubeconfig)))
This will output the following on Windows:
$USERPROFILE/.kube/config
C:\Users\username/.kube/config
C:\Users\username\.kube\config
精彩评论