Skip to content
This repository was archived by the owner on Apr 7, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Sources/HTTPKit/Server/HTTPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,14 @@ public final class HTTPServer {

public let configuration: Configuration
public let eventLoopGroup: EventLoopGroup


// MARK: Properties

/// The port the `HTTPServer` is bound to.
///
/// Nil if `HTTPServer` is not bound to an IP port (eg. serving from a Unix socket or some other exotic channel).
public var port: Int? { return channel?.localAddress?.port }

private var channel: Channel?
private var quiesce: ServerQuiescingHelper?

Expand Down
39 changes: 35 additions & 4 deletions Tests/HTTPKitTests/HTTPServerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class HTTPServerTests: XCTestCase {
let server = HTTPServer(
configuration: .init(
hostname: "localhost",
port: 8080,
port: 0,
supportVersions: [.one],
errorHandler: { error in
XCTFail("\(error)")
Expand All @@ -24,14 +24,45 @@ class HTTPServerTests: XCTestCase {
on: self.eventLoopGroup
)
try server.start(delegate: LargeResponder()).wait()
defer {
try! server.shutdown().wait()
try! server.onClose.wait()
}

var req = HTTPRequest(method: .GET, url: "http://localhost:8080/")
var req = HTTPRequest(method: .GET, url: "http://localhost:\(server.port!)/")
req.headers.replaceOrAdd(name: .connection, value: "close")
let res = try HTTPClient(on: self.eventLoopGroup)
.send(req).wait()
XCTAssertEqual(res.body.count, 2_000_000)
try server.shutdown().wait()
try server.onClose.wait()
}

func testServerPort() throws {
struct Responder: HTTPServerDelegate {
func respond(to request: HTTPRequest, on channel: Channel) -> EventLoopFuture<HTTPResponse> {
let res = HTTPResponse(status: .ok, body: "OK")
return channel.eventLoop.makeSucceededFuture(res)
}
}

let server = HTTPServer(
configuration: .init(
hostname: "localhost",
port: 0,
supportVersions: [.one],
errorHandler: { error in
XCTFail("\(error)")
}
),
on: self.eventLoopGroup
)
try server.start(delegate: Responder()).wait()
defer {
try! server.shutdown().wait()
try! server.onClose.wait()
}

XCTAssertNotNil(server.port)
XCTAssertGreaterThan(server.port!, 0)
}

func testRFC1123Flip() throws {
Expand Down
1 change: 1 addition & 0 deletions Tests/HTTPKitTests/XCTestManifests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ extension HTTPServerTests {
static let __allTests__HTTPServerTests = [
("testLargeResponseClose", testLargeResponseClose),
("testRFC1123Flip", testRFC1123Flip),
("testServerPort", testServerPort),
]
}

Expand Down