How to add a string to an URL in golang?

huangapple go评论93阅读模式
英文:

How to add a string to an URL in golang?

问题

我是新手学习golang,第一次尝试。我需要调用Yahoo Finance API(YQL)以JSON格式获取股票符号的股票价格。
这是API链接:

http://query.yahooapis.com/v1/public/yql?q=select%20LastTradePriceOnly%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22AAPL%22,%22FB%22,%22GOOG%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys

目前我在上述查询中硬编码了符号(AAPL,FB,GOOG),但这些符号将来自用户,应该是动态的。在golang中,我应该如何将输入(符号)添加到上述查询中?

提前感谢您的帮助。

英文:

I am new to golang and trying this for the first time. I have to call yahoo finance api(YQL) to get the stock price of the symbol in json format.
Here is the api:

http://query.yahooapis.com/v1/public/yql?q=select%20LastTradePriceOnly%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22AAPL%22,%22FB%22,%22GOOG%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys

For now i have hard coded the symbol(AAPL,FB, GOOG) in the above select query but these symbols will be coming from the user, it should be dynamic. How should i add the input(symbol) to the above query in golang?

Thanks for the help in advance.

答案1

得分: 0

如果你有作为字符串数组参数的符号(由用户提供),例如:symbols,可以使用strings/#Join函数生成正确的字符串:

s := strings.Join(symbols, ",")

然后,根据“编码/解码URL”的详细说明,使用net/url/#QueryEscape函数获取符号的最终URL字符串:

url := "http://query.yahooapis.com/v1/public/yql?q=select%20LastTradePriceOnly%20from%20yahoo.finance.quote%20where%20symbol%20in%20(" +
url.QueryEscape(s) +
")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
英文:

If you have the symbols (provided by the users) as a string array parameter (like: "symbols", being string["\"AAPL\"", "\"FB\"", "\"GOOG\""]), you can use strings/#Join to produce the right string:

s := strings.Joins(symbols, ",")

Then (as detailed in "Encode / decode URLs"), use net/url/#QueryEscape to get the final url string for symbols:

url := "http://query.yahooapis.com/v1/public/yql?q=select%20LastTradePriceOnly%20from%20yahoo.finance.quote%20where%20symbol%20in%20(" + 
url.QueryEscape(s) + 
")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"

huangapple
  • 本文由 发表于 2015年9月27日 09:18:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/32803642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定