DomainDig/DomainHostURL.swift
30 lines · 1141 bytes
4 symbols in this file
1import Foundation
2
3/// Request URLs for an inspected host.
4///
5/// The inspected domain is free text, so it cannot be forced into a URL:
6/// `URL(string: "https://exa mple.com")` is nil, and a section service that
7/// built its request with `!` trapped on any host carrying a space, a tab or a
8/// control character — reachable by typing `example .com`, or by separating
9/// bulk input with spaces instead of commas or newlines.
10enum DomainHostURL {
11 static func https(_ host: String) -> URL? {
12 url(scheme: "https", host: host)
13 }
14
15 static func http(_ host: String) -> URL? {
16 url(scheme: "http", host: host)
17 }
18
19 /// `nil` when `host` cannot form a URL with a host component.
20 static func url(scheme: String, host: String) -> URL? {
21 let trimmedHost = host.trimmingCharacters(in: .whitespacesAndNewlines)
22 guard !trimmedHost.isEmpty,
23 trimmedHost.rangeOfCharacter(from: .whitespacesAndNewlines) == nil,
24 let url = URL(string: "\(scheme)://\(trimmedHost)"),
25 url.host?.isEmpty == false else {
26 return nil
27 }
28 return url
29 }
30}