net.IP没有实现net.Addr(缺少Network方法)

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

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.

huangapple
  • 本文由 发表于 2016年11月4日 22:43:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/40425479.html
匿名

发表评论

匿名网友

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

确定