From 5c207f5b2a0a80d6689561aea70a814920e5267a Mon Sep 17 00:00:00 2001 From: Ziya Suzen Date: Sun, 28 Apr 2024 18:14:34 +0100 Subject: [PATCH] Fixed wobsocket path Allow path to be passed into websocket connection so that if there is a proxy in between it can be setup with a path on the proxy server even though it doesn't matter for the server connection. Also there is a future option we can introduce to pass HTTP headers in case application might use them to authenticate with the proxy for example. --- Sources/Nats/HTTPUpgradeRequestHandler.swift | 22 +++++++++++++++++--- Sources/Nats/NatsConnection.swift | 8 ++++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/Sources/Nats/HTTPUpgradeRequestHandler.swift b/Sources/Nats/HTTPUpgradeRequestHandler.swift index a3dc2e1..5949586 100644 --- a/Sources/Nats/HTTPUpgradeRequestHandler.swift +++ b/Sources/Nats/HTTPUpgradeRequestHandler.swift @@ -21,13 +21,18 @@ internal final class HTTPUpgradeRequestHandler: ChannelInboundHandler, Removable typealias OutboundOut = HTTPClientRequestPart let host: String - let headers = HTTPHeaders() + let path: String + let query: String? + let headers: HTTPHeaders let upgradePromise: EventLoopPromise private var requestSent = false - init(host: String, upgradePromise: EventLoopPromise) { + init(host: String, path: String, query: String?, headers: HTTPHeaders, upgradePromise: EventLoopPromise) { self.host = host + self.path = path + self.query = query + self.headers = headers self.upgradePromise = upgradePromise } @@ -52,10 +57,21 @@ internal final class HTTPUpgradeRequestHandler: ChannelInboundHandler, Removable var headers = self.headers headers.add(name: "Host", value: self.host) + var uri: String + if self.path.hasPrefix("/") || self.path.hasPrefix("ws://") || self.path.hasPrefix("wss://") { + uri = self.path + } else { + uri = "/" + self.path + } + + if let query = self.query { + uri += "?\(query)" + } + let requestHead = HTTPRequestHead( version: HTTPVersion(major: 1, minor: 1), method: .GET, - uri: "/", + uri: uri, headers: headers ) context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) diff --git a/Sources/Nats/NatsConnection.swift b/Sources/Nats/NatsConnection.swift index 22bb176..4a6f7f9 100644 --- a/Sources/Nats/NatsConnection.swift +++ b/Sources/Nats/NatsConnection.swift @@ -434,10 +434,12 @@ class ConnectionHandler: ChannelInboundHandler { } } else { if server.scheme == "ws" || server.scheme == "wss" { - let host = server.host ?? "localhost" - let port = server.port ?? 80 let httpUpgradeRequestHandler = HTTPUpgradeRequestHandler( - host: "\(host):\(port)", upgradePromise: upgradePromise) + host: server.host ?? "localhost", + path: server.path, + query: server.query, + headers: HTTPHeaders(), // TODO (mtmk): pass in from client options + upgradePromise: upgradePromise) let httpUpgradeRequestHandlerBox = NIOLoopBound( httpUpgradeRequestHandler, eventLoop: channel.eventLoop)