英文:
Get Golang flags as byte array
问题
我正在使用flag
包来读取我传递给我的Golang程序的所有参数。问题是,如果我传递一个参数,例如"\x41BC"
,它不会被读取为一个由字符'A'
,'B'
和'C'
组成的3字节数组,而是被读取为一个由'\x'
,'x'
,'4'
,'1'
,'B'
,'C'
组成的6字节数组。
如果回答有用的话,我是这样读取该字符串的:
flag.StringVar(¶m, "param", "", "the param with hex chars")
有没有办法避免这种情况?
提前谢谢!
英文:
I am using flag
package to read all the parameters I am passing to my Golang program. The problem is that if I pass an argument such as "\x41BC"
, it is not read as a 3 byte array (with chars 'A'
, 'B'
and 'C'
), but as a 6 byte array ('\'
, 'x'
, '4'
, '1'
, 'B'
, 'C'
).
If it could be useful to answer, I am reading that string using:
flag.StringVar(&param, "param", "", "the param with hex chars")
Is there a way to avoid this?
Thanks in advance!
答案1
得分: 5
"\x41BC
" 是一个带引号的字符串。flag
包不会对其进行解引号,它只会将在启动应用程序时指定的参数传递给你。你可以使用 strconv.Unquote()
和 strconv.UnquoteChar()
函数来解引号。
你需要注意的一点是,strconv.Unquote()
只能解引号的字符串(例如以引号字符 "
或反引号字符 `
开始和结束的字符串),所以我们需要手动添加引号。
看下面的例子:
s := `\x41BC`
fmt.Println(s)
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
panic(err)
}
fmt.Println(s2)
输出结果(在 Go Playground 上尝试):
\x41BC
ABC
因此,如果你想要能够提供带引号的字符串作为命令行参数,并且仍然获得解引号后的值,你需要在调用 flag.Parse()
后使用 strconv.Unquote()
进行解引号,例如:
var param string
flag.StringVar(¶m, "param", "", "the param with hex chars")
flag.Parse()
var err error
param, err = strconv.Unquote(`"` + param + `"`)
if err != nil {
panic(err) // 处理错误
}
// param 现在包含了解引号后的参数值
英文:
"\x41BC"
is a quoted string. The flag
package does not do any unquoting, it will just hand you over the arguments that were specified when starting your application. You can use the strconv.Unquote()
and strconv.UnquoteChar()
functions to unquote them.
One thing you should be aware of is that strconv.Unquote()
can only unquote strings that are in quotes (e.g. start and end with a quote char "
or a back quote char `
), so we have to manually append that.
See this example:
s := `\x41BC`
fmt.Println(s)
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
panic(err)
}
fmt.Println(s2)
Output (try it on the Go Playground):
\x41BC
ABC
So if you want to be able to provide quoted strings as command line arguments and still have the unquoted values, you have to unquote them with strconv.Unquote()
after calling flag.Parse()
, for example:
var param string
flag.StringVar(&param, "param", "", "the param with hex chars")
flag.Parse()
var err error
param, err = strconv.Unquote(`"` + param + `"`)
if err != nil {
panic(err) // handle error
}
// param now contains the unquoted argument value
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论