Skip to content

Commit 7727770

Browse files
authored
Add URL Host parser and test (#32)
* Fix incorrect Scheme parser comment * Add Host parser and tests
1 parent d4d6c3b commit 7727770

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

Sources/URLRouting/Host.swift

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/// Parses a request's host.
2+
///
3+
/// Used to require a particular host at a particular endpoint.
4+
///
5+
/// ```swift
6+
/// Route(.case(SiteRoute.custom)) {
7+
/// Host("custom") // Only routes scheme://custom requests
8+
/// ...
9+
/// }
10+
/// ```
11+
///
12+
/// > Note: Do not use the `Host` parser for the purpose of preferring to print a particular
13+
/// > host from your router. Instead, consider using ``BaseURLPrinter`` via the `baseURL` and
14+
/// > `baseRequestData` methods on routers.
15+
public struct Host: ParserPrinter {
16+
@usableFromInline
17+
let name: String
18+
19+
/// A parser of custom hosts.
20+
public static func custom(_ host: String) -> Self {
21+
Self(host)
22+
}
23+
24+
/// Initializes a host parser with a host name.
25+
///
26+
/// - Parameter name: A host name.
27+
@inlinable
28+
public init(_ name: String) {
29+
self.name = name
30+
}
31+
32+
@inlinable
33+
public func parse(_ input: inout URLRequestData) throws {
34+
guard let host = input.host else { throw RoutingError() }
35+
try self.name.parse(host)
36+
input.host = nil
37+
}
38+
39+
@inlinable
40+
public func print(_ output: (), into input: inout URLRequestData) {
41+
input.host = self.name
42+
}
43+
}

Sources/URLRouting/Scheme.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public struct Scheme: ParserPrinter {
2424

2525
/// Initializes a scheme parser with a scheme name.
2626
///
27-
/// - Parameter name: A method name.
27+
/// - Parameter name: A scheme name.
2828
@inlinable
2929
public init(_ name: String) {
3030
self.name = name

Tests/URLRoutingTests/URLRoutingTests.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ class URLRoutingTests: XCTestCase {
1212
XCTAssertEqual(try Method.post.print(), URLRequestData(method: "POST"))
1313
}
1414

15+
func testHost() {
16+
XCTAssertNoThrow(try Host.custom("foo").parse(URLRequestData(host: "foo")))
17+
XCTAssertEqual(try Host.custom("foo").print(), URLRequestData(host: "foo"))
18+
}
19+
1520
func testScheme() {
1621
XCTAssertNoThrow(try Scheme.http.parse(URLRequestData(scheme: "http")))
1722
XCTAssertEqual(try Scheme.http.print(), URLRequestData(scheme: "http"))

0 commit comments

Comments
 (0)