英文:
How to specify a windows file path in a Go application?
问题
我正在尝试为Go客户端应用程序指定.kube/config文件的Windows位置,而不指定绝对路径。
kubeconfig := flag.String("kubeconfig", "%USERPROFILE%/.kube/config", "Kube配置文件的位置")
输出:
panic: 运行时错误:无效的内存地址或空指针解引用
当我在cmd中使用echo %USERPROFILE%
时,输出是C:\Users\<username>
,所以我认为这是由于代码和路径中\
和/
的不同用法。
我尝试使用\
而不是/
来指定路径,但它会产生语法错误。
有人能给我提供一个解决方案,以在Go应用程序中使用Windows环境变量来指定路径吗?
提前感谢。
英文:
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 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.
答案1
得分: 2
flag.String
本身不会展开环境变量,但你可以使用os.ExpandEnv
来实现。然而,os.ExpandEnv
要求你使用Unix符号表示环境变量,即$USERPROFILE
或${USERPROFILE}
。你可以使用filepath.Clean
来获取特定操作系统(在你的情况下是Windows)的干净文件路径。
示例:
kubeconfig := flag.String("kubeconfig", "$USERPROFILE/.kube/config", "Kube配置文件的位置")
fmt.Println(*kubeconfig)
fmt.Println(os.ExpandEnv(*kubeconfig))
fmt.Println(filepath.Clean(os.ExpandEnv(*kubeconfig)))
在Windows上,这将输出以下内容:
$USERPROFILE/.kube/config
C:\Users\username/.kube/config
C:\Users\username\.kube\config
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论