获取WebSocket中的完整URL

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

Get full URL in WebSocket

问题

我正在使用其中一个golang示例构建一个WebSocket服务器。根据示例,结构体Client在这里访问websocket.Conn,而websocket.Conn有一个返回*http.RequestRequest方法。

我的想法是根据用户使用的子域名订阅不同的频道,以便他们进入应用程序。

那么,在用户订阅WebSocket时,是否可以获取用户访问的完整URL?使用示例代码,我认为ws.Conn.Request().URL.Host会给我类似于ws://channel1.lvh.me:8080/sync的内容,但实际上我得到的是路径:"/chat"。

是否可以获取用户用于连接WebSocket的完整URL?提前感谢。

英文:

I'm using one of the golang samples to build a WebSocket server. According to the samples the struct Client access websocket.Conn here and websocket.Conn has a Request method returning *http.Request.

My idea is to subscribe the user to different channels depending on the subdomain they use to enter the app.

So is it possible to get the full URL the user hit when subscribed to the websocket? Using the sample code I thought ws.Conn.Request().URL.Host would give me something like ws://channel1.lvh.me:8080/sync but instead I'm getting the path: "/chat".

Is it possible to get the full URL the user used to connect to the websocket? Thanks in advance.

答案1

得分: 1

检查主机头以获取请求的主机:

host := c.Request().Host

Request.URL字段是从HTTP请求URI解析的。对于大多数请求,请求URI只包含路径和查询。

应用程序可以通过主机头和应用程序提供的协议知识重建完整的URL。例如,如果应用程序正在监听HTTP请求(或使用HTTP进行握手的WS请求),完整的URL是:

u := *c.Request().URL
u.Host = c.Request().Host
u.Scheme = "http"
英文:

Examine the host header to get the requested host:

host := c.Request().Host

The Request.URL field is parsed from the HTTP request URI. For most requests, the request URI contains path and query only.

An application can reconstruct a full URL from the host header and knowledge of the protocols the application is serving. For example, if the application is listening for HTTP requests (or WS request that use HTTP for handshake), the full URL is:

u := *c.Request().URL
u.Host = c.Request().Host
u.Scheme = "http"

答案2

得分: 0

func (*Conn) Request 返回 *http.Request

func (ws *Conn) Request() *http.Request

检查来自 http 包的 http.Request,你会发现它具有 URL *url.URL 类型。这意味着你可以通过以下方式获取完整的 URL:

ws.Request().URL.Path
英文:

func (*Conn) Request returns *http.Request

func (ws *Conn) Request() *http.Request

Checking the http.Request from the http package you will observe that it has a URL *url.URL type. This means that you should get the full url with:

ws.Request().URL.Path

huangapple
  • 本文由 发表于 2016年2月25日 16:33:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/35622107.html
匿名

发表评论

匿名网友

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

确定