drtpbx3606 2017-10-16 12:49
浏览 64
已采纳

如何在Golang中解析/创建动态网址

I am trying to create a buildURL function that can generate an url. However I have run into a problem when facing a dynamic url.

type ShopifyDownloader struct {
    Domain      string
    AccessToken string
}

func (sd *ShopifyDownloader) BuildURL(Path string, Query map[string]string) (string, error) {
    u, err := url.Parse("https://123.myshopify.com/admin/orders/count.json?access_token=123")
    if err != nil {
        fmt.Println("Cannot parse", err)
        return "", err
    }
    u.Host = sd.Domain
    u.Path = Path
    params := url.Values{}
    for key, value := range Query {
        params.Add(key, value)
    }
    u.RawQuery = params.Encode()
    nu := u.String()
    var buffer bytes.Buffer
    buffer.WriteString(nu)
    buffer.WriteString("?access_token=")
    buffer.WriteString(sd.AccessToken)
    bu := buffer.String()
    return bu, err
}

It takes domain, token, path and queries and generate an url in string. However it does not work with a dynamic path (with id) like this /admin/orders/#{id}.json or this /admin/products/#{id}/images/#{id}.json Does anybody have any suggestion?

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-10-16 20:02
    关注

    Why not just build a url with something simpler at the point where you use it?

    url := fmt.Sprintf("%s/admin/orders/count.json?access_token=%s&custom=%s",sd.Domain,sd.Token,customparam)
    

    Then use it. This has the virtue of being completely clear as to intent and the url used in each case while sharing the important stuff (shopify domain etc). Then for your question about ids it becomes easier:

    url := fmt.Sprintf("%s/admin/orders/%d.json?access_token=%s",sd.Domain,orderID,sd.Token)
    

    and

    url := fmt.Sprintf("%s/admin/products/%d/images/%d.json?access_token=%s",sd.Domain,productID,imageID,sd.Token)
    

    if you feel your params are super complex (for me this would have to be at least 5), just put them in an url.Values (including the token):

    params := url.Values{"myparam":{"123"}, "token": {sd.Token}}
    url := fmt.Sprintf("%s/admin/orders/count.json?%s", sd.Domain, 
    params.Encode())
    

    but this is only worthwhile if you have a significant number of params.

    If you want to add functions to ShopifyDownloader, why force the caller to define the url structure? Try to make it simpler for them. You don't need to parse urls or write to a bytes buffer, http.Get expects a string, so work with strings. If you want to build functions, consider instead having separate functions which know about the url formats, to abstract this away from the caller, so :

     func (sd *ShopifyDownloader) OrderURL(orderID int, params url.Values) string {
            params["token"] = []string{sd.AccessToken}
            return fmt.Sprintf("%s/admin/orders/%d.json?%s",sd.Domain,orderID,params)
        }
    

    The caller should not know about the specific format of Shopify urls, which may change (just as the endpoint may change).

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分