如何更改 go-fiber 客户端使用的 IP 地址?

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

How to change which IP address a go-fiber client is using?

问题

我正在使用Fiber作为HTTP客户端向HTTP服务器发送请求,但是我遇到了速率限制的问题。在我的虚拟机上,我配置了5个不同的IP地址(公共/私有),并确认它们确实连接到了互联网。

curl --interface 10.0.0.4 ipinfo.io/json
curl --interface 10.0.0.5 ipinfo.io/json
...
curl --interface 10.0.0.8 ipinfo.io/json

每个命令返回一个不同的公共IP地址。

现在我想使用这些本地地址进行轮询请求,但是我不太确定如何操作。

是否有一种属性或函数可以设置/调用,以更改出站请求的来源?

我查看了fasthttp.HostClient,它是fiber.Agent的扩展,但是我没有找到有用的信息。

谢谢大家。

英文:

I'm using Fiber as an HTTP client to make some requests to an http server, however I'm being rate limited. On my vm I configured 5 different IP addresses (public/private) and have confirmed that they are indeed connected to the internet.

curl --interface 10.0.0.4 ipinfo.io/json
curl --interface 10.0.0.5 ipinfo.io/json
...
curl --interface 10.0.0.8 ipinfo.io/json

each one returns a different public facing ip address.

Now I'm interested in making round-robin requests using these local addresses but I'm not so sure how to go about it.

Is there some sort of property or function I can set/call to change where the outgoing request is coming from?

I've looked around at fasthttp.HostClient which fiber.Agent extends but I didn't see anything useful.

Thanks guys.

答案1

得分: 1

a := fiber.AcquireAgent()
req := a.Request()
req.Header.SetMethod(fiber.MethodGet)
req.SetRequestURI(fmt.Sprintf(formatUrl, args...))

if err := a.Parse(); err != nil {
	h.Logger.Error("%v", err)
	return fiber.StatusInternalServerError, nil, []error{err}
}

customDialer := fasthttp.TCPDialer{
	Concurrency: 1000,
	LocalAddr: &net.TCPAddr{
		IP: h.IPPool[atomic.AddUint32(&h.IpIdx, 1)%uint32(len(h.IPPool))],
	},
}

a.HostClient.Dial = func(addr string) (net.Conn, error) {
	return customDialer.Dial(addr)
}

创建一个自定义的拨号器和拨号函数可以更改与HTTP请求关联的本地地址。

英文:
a := fiber.AcquireAgent()
req := a.Request()
req.Header.SetMethod(fiber.MethodGet)
req.SetRequestURI(fmt.Sprintf(formatUrl, args...))

if err := a.Parse(); err != nil {
	h.Logger.Error("%v", err)
	return fiber.StatusInternalServerError, nil, []error{err}
}

customDialer := fasthttp.TCPDialer{
	Concurrency: 1000,
	LocalAddr: &net.TCPAddr{
		IP: h.IPPool[atomic.AddUint32(&h.IpIdx, 1)%uint32(len(h.IPPool))],
	},
}

a.HostClient.Dial = func(addr string) (net.Conn, error) {
	return customDialer.Dial(addr)
}

Creating a custom dialer and dial func allows you to change the local address associated with the http request.

huangapple
  • 本文由 发表于 2022年11月9日 02:45:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/74365722.html
匿名

发表评论

匿名网友

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

确定