netpoll
netpoll copied to clipboard
How to use a context in client api?
Tried to implement a simple proxy server, as the case in #102.
If I'm correct, OnRequest
is called every time when a connection is readable. As a large request may be split into multiple packets, is it correct to loop read in the OnRequest
callback?
I want to pass the client connection into the context of the downstream client connection:
In server OnConnection
: create a downstream client connection, attach server connection to it in its context.
In server OnRequest
: get the downstream connection from context, forward every bytes in requests.
In downstream client OnRequest
: get attached server connection, write every bytes of responses back through it.
It's easy to implement in java/netty. How can I do this using netpoll
? Or any better approach. Thank you.
Hi, @gonwan
As a large request may be split into multiple packets, is it correct to loop read in the OnRequest callback?
You can loop read in OnRequest. And you can use ".Next(n)" API , if there is no enough readable data, it will block and triggered when new data coming.
And you can return the ctx attached the "downstream client connection" and then OnRequest can get that ctx. There is a comment show you a example:
Thanks for your info, I've already read the comment.
Three roles: the original client, the original server, the downstream client. The sample shows how to attach the connection of downstream client to the ctx of the original server(so that I can get and forward request to it in onRequest
). But I want to do the opposite, attach the incoming connection of the original server to the ctx of the downstream client(so that I can get and forward response). I cannot find an API...
@gonwan I cannot understand very well about what you mean.. could you give me a graph of your proxy's call-chain ?
Hi, @gonwan
As a large request may be split into multiple packets, is it correct to loop read in the OnRequest callback?
You can loop read in OnRequest. And you can use ".Next(n)" API , if there is no enough readable data, it will block and triggered when new data coming.
And you can return the ctx attached the "downstream client connection" and then OnRequest can get that ctx. There is a comment show you a example:
能否支持通过DialConnection、DialTCP等API建立一个链接时,也可以绑定一个context。
@joway 就是想实现一个简单的类似haproxy的tcp代理。只是说调用客户端api的时候,也可以绑定一个context可以用来传递额外参数。
@Emove yep, that's what i suggested to have...
@gonwan I think this feature can implement on user side? for example :
type MyConn struct { conn netpoll.Connection args ... }
@joway 可以这样实现。不过添加context支持到客户端api,保持了跟服务端api的一致性。如果理解正确的话,对于客户端api来说,context参数在所有OnXXXXX()回调里完全是空的,没有用。
@gonwan I think this feature can implement on user side? for example :
type MyConn struct { conn netpoll.Connection args ... }
通过这种方式也无法满足为各个连接绑定特定的额外参数
这个需求可以考虑在后面的版本中加上
https://github.com/cloudwego/netpoll/pull/298 这个 PR 间接让 dialer 也支持了 netpoll.Option 进而可以使用 OnConnect/OnPrepare 来传递 ctx 给 OnRequest