Skip to content

Commit

Permalink
Improved parsing of subdomains so IP-like domains get properly parsed
Browse files Browse the repository at this point in the history
  • Loading branch information
dimitribouniol committed Jan 11, 2024
1 parent 617adc9 commit dc40e56
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
13 changes: 11 additions & 2 deletions Sources/HostRouter/HostComponent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,20 @@ extension HostComponent: CustomStringConvertible {

extension StringProtocol {
/// Converts a host (either a domain or an IP address) into a reversed collection of ``HostComponent``s.
@inlinable
public var reversedDomainComponents: [HostComponent] {
guard !self.isIPAddress else { return [.constant(String(self))] }
return self.split(separator: ".").reversed().map { .init(stringLiteral: $0.lowercased()) }
return reversedSubDomainComponents
}

/// Converts a subdomain into a reversed collection of ``HostComponent``s.
@inlinable
public var reversedSubDomainComponents: [HostComponent] {
self.split(separator: ".").reversed().map { .init(stringLiteral: $0.lowercased()) }
}

/// Retrieve the port and domain from the receiving Host string.
@usableFromInline
var hostComponents: (port: String?, reverseDomain: [String]) {
let baseComponents = self.split(separator: ":")
let (host, port) = baseComponents.count == 2 ? (String(baseComponents[0]), String(baseComponents[1])) : (String(self), nil)
Expand All @@ -52,7 +60,8 @@ extension StringProtocol {
}

/// Check if the string is an IP address.
private var isIPAddress: Bool {
@usableFromInline
var isIPAddress: Bool {
// TODO: This was unused in Vapor, and NIO may have a better helper for this.

/// We need some scratch space to let inet_pton write into.
Expand Down
4 changes: 2 additions & 2 deletions Sources/HostRouter/HostRoutesGroup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ extension TopLevelHostRoutesBuilder {

extension HostRoutesBuilder {
public func grouped(subDomain: some StringProtocol) -> some HostRoutesBuilder {
HostRoutesGroup(root: self, port: nil, domainPath: subDomain.reversedDomainComponents)
HostRoutesGroup(root: self, port: nil, domainPath: subDomain.reversedSubDomainComponents)
}

public func grouped(reverseDomain: HostComponent...) -> some HostRoutesBuilder {
Expand All @@ -52,7 +52,7 @@ extension HostRoutesBuilder {
}

public func group(subDomain: some StringProtocol, configure: (HostRoutesBuilder) throws -> ()) rethrows {
try configure(HostRoutesGroup(root: self, port: nil, domainPath: subDomain.reversedDomainComponents))
try configure(HostRoutesGroup(root: self, port: nil, domainPath: subDomain.reversedSubDomainComponents))
}

public func group(reverseDomain: HostComponent..., configure: (HostRoutesBuilder) throws -> ()) rethrows {
Expand Down

0 comments on commit dc40e56

Please sign in to comment.