英文:
net.IP does not implement net.Addr (missing Network method)
问题
我有以下代码。我得到了这个错误:
testdl.go:17: cannot use q (type net.IP) as type net.Addr in field value:
net.IP does not implement net.Addr (missing Network method)
有什么办法可以将硬编码的IP放入LocalAddr中吗?
package main
import (
"fmt"
"net"
"net/http"
)
var url = "http://URL/api.xml"
func main() {
q := net.ParseIP("192.168.0.1")
var transport = &http.Transport{
Dial: (&net.Dialer{
LocalAddr: q,
}).Dial,
}
var httpclient = &http.Client{
Transport: transport,
}
response, err := httpclient.Get(url)
fmt.Println(response)
}
英文:
I have the following code. I'm getting this error:
testdl.go:17: cannot use q (type net.IP) as type net.Addr in field value:
net.IP does not implement net.Addr (missing Network method)
Any idea how to put a hardcoded IP into LocalAddr?
package main
import (
"fmt"
"net"
"net/http"
)
var url = "http://URL/api.xml"
func main() {
q := net.ParseIP("192.168.0.1")
var transport = &http.Transport{
Dial: (&net.Dialer{
LocalAddr: q,
}).Dial,
}
var httpclient = &http.Client{
Transport: transport,
}
response, err := httpclient.Get(url)
fmt.Println(response)
}
答案1
得分: 6
根据文档,确实IP
类型没有实现Addr
。然而,IPAddr
类型实现了Addr
接口:
type IPAddr struct {
IP IP
Zone string // IPv6 scoped addressing zone
}
因此,你的代码应该修改为:
q := net.ParseIP("192.168.0.1")
addr := &net.IPAddr{IP: q, Zone: ""}
var transport = &http.Transport{
Dial: (&net.Dialer{
LocalAddr: addr,
}).Dial,
}
英文:
According to the documentation, indeed the IP
type does not implement Addr
. However, the type IPAddr
does:
type IPAddr struct {
IP IP
Zone string // IPv6 scoped addressing zone
}
Therefore, your code becomes:
q := net.ParseIP("192.168.0.1")
addr := &net.IPAddr{q,""}
var transport = &http.Transport{
Dial: (&net.Dialer{
LocalAddr: addr,
}).Dial,
}
答案2
得分: 3
使用文档,卢克...
https://golang.org/pkg/net/#ResolveIPAddr
如果你使用IPAddr结构体,那应该可以解决你的问题。
英文:
Use the Docs, Luke...
https://golang.org/pkg/net/#ResolveIPAddr
If you use the IPAddr struct, that should solve your problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论