在反向代理中正确响应客户端

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

Respond to the right client in a Reverse proxy

问题

我正在尝试使用Go语言在两台服务器之间建立一个持久的TCP连接:一个位于本地的client和一个位于远程机器上的server。客户端还会本地提供HTTP请求给一个PHP脚本。每个请求都会通过TCP连接中继到远程服务器,然后将响应发送回PHP脚本。

使用并发连接时,发送到远程服务器和返回的请求不会同步,也就是说,对于请求#1的响应可能会发送给请求#2。

我目前的解决方案

我创建了一个由唯一ID标识的通道的映射map,每个HTTP请求都有一个唯一的ID。这个唯一ID在TCP请求中传递给服务器,并在响应中一起发送回来。客户端解析响应中的ID,并将其发送到数组中对应的通道。下面是一个简化的代码示例,其中conns是可用通道的map,唯一ID是整个响应或str

connbuf := bufio.NewReader(remoteConn)	
str, err := connbuf.ReadString('\n')
str = strings.TrimSpace(str)
if len(str) > 0 {
    id, _ := strconv.Atoi(str)
    conns[id] <- str
}

问题

是否有更优雅、内置的方法来实现这一点,以确保即使在并发请求的情况下,对本地PHP脚本的请求和响应也是正确的?

英文:

I'm trying to build a persistent TCP connection between two servers using Go; A client that resides locally and server in the remote machine. The client also serves HTTP requests locally to a PHP script. Each request is relayed through the TCP connection to the remote server. The response is then sent back to the PHP script.

HTTP request from .php script
  \
   \    -----&gt; HTTP req is relayed
    \                 
client &lt;--------------TCP connection------------&gt; server
    / 
   /              &lt;------ Response is relayed
  /
HTTP request from .php script

With concurrent connections, the requests sent to and back from the remote server aren't synchronized, i.e. the response for request #1 could be sent to request #2 instead.

My current solution

I've created a map of channels that are identified by a unique ID per HTTP request. This unique ID is passed in the TCP request to the server and is sent back along with the response. The client parses this ID in the response and sends it to the corresponding channel in the array. Oversimplified code where conns is the map of available channels and the unique ID is the whole response, or str:

    connbuf := bufio.NewReader(remoteConn)	
	str, err := connbuf.ReadString(&#39;\n&#39;)
	str = strings.TrimSpace(str)
	if len(str) &gt; 0 {
		id, _ := strconv.Atoi(str)
		conns[id] &lt;- str
	}

Question

Is there a more elegant, built-in way to achieve this - making sure requests and responses to the local PHP script are correct even with concurrent requests?

答案1

得分: 1

这在很大程度上是kouton的自我回答,但是使用单个“后端”连接(在本地服务器和远程服务器之间)来为多个“前端”连接(在本地PHP和本地服务器之间)提供服务是一种多路复用的形式,muxado包(演讲视频)旨在帮助您实现它。

英文:

This is as much a self-answer by kouton as anything, but using a single "back end" connection (between your local server and the remote server) to service multiple "front end" connections (between your local PHP and the local server) is a form of multiplexing, and the muxado package (video of a talk) is meant to help you implement it.

huangapple
  • 本文由 发表于 2014年8月2日 11:49:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/25091480.html
匿名

发表评论

匿名网友

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

确定