2017-05-06 23:38 阅读 668

如何使用Golang HTTP客户端正确设置URL中的路径参数?

I'm using net/http package and i would like to set dynamic values to an POST url:{id}/whatever

How can i set id values in this path parameter?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    ds3016 ds3016 2017-05-07 17:47

    If you are trying to add params to a URL before you make a server request you can do something like this.

    const (
        sellersURL = ""
    q := url.Values{}
    q.Add("id", "1")
    req, err := http.NewRequest("POST", sellersURL, strings.NewReader(q.Encode()))
    if err != nil {
        return err
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.Close = true
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return err
    点赞 评论 复制链接分享
  • dongqiang2069 dongqiang2069 2017-05-07 19:12

    There is one place where I saw more elegant way to do this (without fmt.Sprintf): uritemplates

    点赞 评论 复制链接分享