英文:
How to do interpolation on URL in Golang
问题
我有以下URL,并且我想要在每次迭代中更改start
的值。有没有更好的方法来做到这一点?
test := "https://www.googleapis.com/customsearch/v1?start=%d&cx=001106611627702700888%3Aaonktv-oz_w&q=bells%20palsy%20mouth&exactTerms=palsy&fileType=png&imgColorType=color&imgType=face&searchType=image&key=AIzaSyAYqQ4IxUHnF7rfvzSvnczxQ-u93AbkC8k"
for v := 1; v < 100; v += 10 {
val := fmt.Sprintf(test, v)
fmt.Println(val)
}
当前输出为:
https://www.googleapis.com/customsearch/v1?start=1&cx=001106611627702700888%!A(MISSING)aonktv-oz_w&q=bells%!p(MISSING)alsy%!m(MISSING)outh&exactTerms=palsy&fileType=png&imgColorType=color&imgType=face&searchType=image&key=AIzaSyAYqQ4IxUHnF7rfvzSvnczxQ-u93AbkC8k
预期输出应为:
https://www.googleapis.com/customsearch/v1?startindex=1&q=bells%20palsy%20mouth
https://www.googleapis.com/customsearch/v1?startindex=11&q=bells%20palsy%20mouth
为什么Sprintf
给我返回(MISSING)
和一些随机字符?
英文:
I have the follow URL and I want to change the value of start
for each iteration. Is there a better way to do it?
test := "https://www.googleapis.com/customsearch/v1?start=%d&cx=001106611627702700888%3Aaonktv-oz_w&q=bells%20palsy%20mouth&exactTerms=palsy&fileType=png&imgColorType=color&imgType=face&searchType=image&key=AIzaSyAYqQ4IxUHnF7rfvzSvnczxQ-u93AbkC8k"
for v := 1; v < 100; v += 10 {
val := fmt.Sprintf(test, v)
fmt.Println(val)
}
Output now:
https://www.googleapis.com/customsearch/v1?start=1&cx=001106611627702700888%!A(MISSING)aonktv-oz_w&q=bells%!p(MISSING)alsy%!m(MISSING)outh&exactTerms=palsy&fileType=png&imgColorType=color&imgType=face&searchType=image&key=AIzaSyAYqQ4IxUHnF7rfvzSvnczxQ-u93AbkC8k
Expected Output should be:
https://www.googleapis.com/customsearch/v1?startindex=1&q=bells%20palsy%20mouth
https://www.googleapis.com/customsearch/v1?startindex=11&q=bells%20palsy%20mouth
....etc.
Why Sprintf
gives me (MISSING)
and a couple of random characters?
答案1
得分: 3
非格式化动词的%
字符应该被转义为%%
:
test := "https://www.googleapis.com/customsearch/v1?start=%d&cx=001106611627702700888%%3Aaonktv-oz_w&q=bells%%20palsy%%20mouth&exactTerms=palsy&fileType=png&imgColorType=color&imgType=face&searchType=image&key=AIzaSyAYqQ4IxUHnF7rfvzSvnczxQ-u93AbkC8k"
如果%
没有被转义,那么fmt期望找到相应的参数,并在找不到参数时输出(MISSING)
。
英文:
The %
characters that are not part of a format verb should be escaped as %%
:
test := "https://www.googleapis.com/customsearch/v1?start=%d&cx=001106611627702700888%%3Aaonktv-oz_w&q=bells%%20palsy%%20mouth&exactTerms=palsy&fileType=png&imgColorType=color&imgType=face&searchType=image&key=AIzaSyAYqQ4IxUHnF7rfvzSvnczxQ-u93AbkC8k"
If the %
are not escaped, then fmt expects to find a corresponding argument and complains with the output (MISSING)
when the argument is not found.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论