如何在Go应用程序中指定Windows文件路径?

huangapple go评论80阅读模式
英文:

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(&quot;kubeconfig&quot;, &quot;%USERPROFILE%/.kube/config&quot;, &quot;location to the Kube config file&quot;)

Output :

panic: runtime error: invalid memory address or nil pointer dereference 

When I use echo %USERPROFILE% in a cmd, the output is C:\Users\&lt;username&gt;, 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(&quot;kubeconfig&quot;, &quot;$USERPROFILE/.kube/config&quot;, &quot;location to the Kube config file&quot;)
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

huangapple
  • 本文由 发表于 2022年12月7日 10:34:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/74711121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定