dongyun3897 2019-04-06 02:22
浏览 103
已采纳

如何在Golang中将标志变量传递给http.Get

I have a block of code which hardcodes the URL required for REST API that I am consuming. What I would like to do is, use the two flags to dynamically generate the URL. For example, something to the effect of:

response, err := http.Get("https://swapi.co/api/%s/1", resourcePtr)

My current code is as follows:

func main() {

    resourcePtr := flag.String("resource", "", "a string")
    idPtr := flag.Int("id", 1, "an int")

    flag.Parse()

    response, err := http.Get("https://swapi.co/api/planets/1")
    if err != nil {
        fmt.Printf("HTTP request failed with error %s
", err)
    } else {
        data, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(data))
    }

}

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongzhui2636 2019-04-06 02:39
    关注

    That's what fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) is for.

    response, err := http.Get(fmt.Sprintf("https://swapi.co/api/%s/1", resourcePtr))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 求帮看看那里的问题ssh项目报错
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题
  • ¥20 有谁能看看我coe文件到底哪儿有问题吗?
  • ¥20 我的这个coe文件到底哪儿出问题了
  • ¥15 matlab使用自定义函数时一直报错输入参数过多
  • ¥15 设计一个温度闭环控制系统