dongren9966
2017-05-06 23:38
浏览 1.5k
已采纳

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

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

http://myhost.com/v1/sellers/{id}/whatever

How can i set id values in this path parameter?

图片转代码服务由CSDN问答提供 功能建议

我正在使用net / http包,我想将动态值设置为POST网址:

http://myhost.com/v1/sellers/ { id} /无论如何

如何在此path参数中设置id值?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • 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 = "http://myhost.com/v1/sellers"
    )
    
    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 2017-05-07 19:12

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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题