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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line