将字符串替换为变量以用于Golang代理

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

Replace string with variable for golang proxy

问题

我正在尝试使用这里的HTTP代理代码:

proxyUrl := url.Parse(strings.Replace("%v", RandomProxyAddress()))
http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}

它告诉我url.Parse中有太多的参数。

但是当我尝试以下代码时:

proxyUrl := url.Parse(RandomProxyAddress())
http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}

我得到了./main.go:138: multiple-value url.Parse() in single-value context的错误。

当我尝试使用字符串替换时,它也告诉我有太多的变量。不确定如何让我的代理与url.Parse一起工作。

英文:

I'm trying to use the http proxy code here

proxyUrl := url.Parse(strings.Replace("%v", RandomProxyAddress()))
http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}

Tells me there are too many arguments in the url.Parse

But when I try

proxyUrl := url.Parse(RandomProxyAddress())
http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}

I get ./main.go:138: multiple-value url.Parse() in single-value context

When I tried a string replace it also tells me too many varibles. Not sure how to get my proxy to work with the url.Parse

答案1

得分: 2

首先,url.Parse函数返回两个变量,一个是URL,另一个是错误。根据这里的文档

其次,你可能想使用fmt.Sprintf("%v", RandomProxyAddress()),而不是strings.Replace,假设RandomProxyAddress()返回一个字符串,或者返回一个可以格式化成你想要的字符串的内容。所以总的来说,你应该有以下代码:

addr := fmt.Sprintf("%v", RandomProxyAddress())
proxyURL, err := url.Parse(addr)
if err != nil {
    log.Println(err)
}

话虽如此,如果RandomProxyAddress()已经返回一个字符串,那么fmt.Sprintf就是不必要的。可以查看fmtfmt.Sprintf的文档。如果你确实想使用strings.Replace,请注意它需要四个参数,而不是两个。

英文:

Firstly, url.Parse returns two variables, a URL and an error, as per the docs here.

Secondly, instead of strings.Replace you probably meant to use fmt.Sprintf("%v", RandomProxyAddress()), assuming RandomProxyAddress() returns a string, or something that formats into the string you want. So all in all, you should have:

addr := fmt.Sprintf("%v", RandomProxyAddress())
proxyURL, err := url.Parse(addr)
if err != nil {
    log.Println(err)
}

That said, the fmt.Sprintf would be unnecessary if RandomProxyAddress() already returns a string. Check the docs for fmt and fmt.Sprintf. And if you really did mean to use strings.Replace, notice that it requires four arguments, not two.

huangapple
  • 本文由 发表于 2016年2月23日 03:01:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/35561719.html
匿名

发表评论

匿名网友

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

确定