在连接到同一客户端的两个不同协议路由之间传递消息的最佳方法是什么?

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

Best way to pass messages between 2 different protocol routes connected to same client

问题

我有一个名为/checkout的HTTP路由,它会在Zeebe中启动一个工作流程。checkout路由会立即向调用客户端返回200响应。然后,工作流程会运行一段时间。为了在完成后将响应推送回客户端,我有一个用于服务器推送事件的独立路由/sse。在这里,我将在一个全局的map中存储所有客户端连接。

我的疑问是,我如何找到准确的客户端,以便通过sse发送响应一次?

  • 示例:客户端A正在监听/sse并调用/checkout端点,该端点将返回200。/sse必须在完成后将响应返回给客户端A

目前,我考虑使用cookie来标识客户端。是否有更好的方法?

英文:

I have a http route /checkout which initiates a workflow process in Zeebe. The checkout route will return 200 response straight-away to calling client. Now, workflow will run for a while. So to push the response back to client after completion, I have a /sse separate route for server-sent events. Here, I will store all the client connection in a global map.

My doubt is how do I find the exact client to send the response back through sse once?

  • Example: Client A listening to /sse and calls /checkout endpoint which will return 200. The /sse has to return the response to client A after completion.

Currently, I thought of using cookie to identify the client. Is there a better way?

答案1

得分: 1

如果您的应用程序已经使用了cookies,那么这是一种可行的方法,因为cookies的目的就是用于识别客户端,所以如果您已经有了cookies,应该使用它。

但是,如果您依赖于其他身份验证机制(比如JWT),您可以将URL用作查询参数。

所以在客户端,不要使用:

let eventSource = new EventSource("/sse");

而是使用:

let eventSource = new EventSource("/sse?authorization=jwt_token");

在后端,您需要验证该令牌,提取客户端ID,并使用该ID访问全局映射以检索相应的连接。

(附注:您应该使用适当的存储方式,如Redis或嵌入式键值存储bbolt,而不是全局映射。)

英文:

If you are already using cookies in your app than that's the way to go since the very purpose of cookies is identifying the client, so if you already have that, you should use it.

But if you rely on another authentication mechanism (like JWT), what you could do is using the url as a query.

So in the client instead of

let eventSource = new EventSource("/sse");

Do

let eventSource = new EventSource("/sse?authorization=jwt_token");

In the backend, you would validate that token, extract the Client ID and hit that global map with it to retrieve the corresponding connection.

(PS: instead of a global map, you should use a proper store, like redis, or an embedded key/value store like bbolt)

huangapple
  • 本文由 发表于 2021年8月30日 22:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/68985933.html
匿名

发表评论

匿名网友

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

确定