英文:
Get full URL in WebSocket
问题
我正在使用其中一个golang示例构建一个WebSocket服务器。根据示例,结构体Client
在这里访问websocket.Conn
,而websocket.Conn
有一个返回*http.Request
的Request
方法。
我的想法是根据用户使用的子域名订阅不同的频道,以便他们进入应用程序。
那么,在用户订阅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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论