获取 Golang 标志作为字节数组。

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

Get Golang flags as byte array

问题

我正在使用flag包来读取我传递给我的Golang程序的所有参数。问题是,如果我传递一个参数,例如"\x41BC",它不会被读取为一个由字符'A''B''C'组成的3字节数组,而是被读取为一个由'\x''x''4''1''B''C'组成的6字节数组。

如果回答有用的话,我是这样读取该字符串的:

flag.StringVar(&param, "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(&param, "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

huangapple
  • 本文由 发表于 2016年3月29日 01:56:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/36267968.html
匿名

发表评论

匿名网友

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

确定