dtjkl42086 2016-04-18 17:13
浏览 59
已采纳

如何在Golang中对URL进行插值

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条回答 默认 最新

  • dpl57372 2016-04-18 17:21
    关注

    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"
    

    playground example

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态