Skip to content

Commit

Permalink
Fixed websocket path
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mtmk authored Apr 29, 2024
1 parent 36bf8c2 commit 64514c3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
26 changes: 23 additions & 3 deletions Sources/Nats/HTTPUpgradeRequestHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,21 @@ 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<Void>

private var requestSent = false

init(host: String, upgradePromise: EventLoopPromise<Void>) {
init(
host: String, path: String, query: String?, headers: HTTPHeaders,
upgradePromise: EventLoopPromise<Void>
) {
self.host = host
self.path = path
self.query = query
self.headers = headers
self.upgradePromise = upgradePromise
}

Expand All @@ -52,10 +60,22 @@ 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)
Expand Down
8 changes: 5 additions & 3 deletions Sources/Nats/NatsConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -438,10 +438,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)

Expand Down

0 comments on commit 64514c3

Please sign in to comment.