Skip to content

Commit 8bcff49

Browse files
authored
Merge pull request #7 from Kyle-Ye/bugfix/kyle/url
Fix extra empty path issue with HttpUrl.init?(url:)
2 parents ae927ad + 4eb4a9c commit 8bcff49

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

Sources/SwiftHttp/HttpUrl.swift

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -237,20 +237,19 @@ extension HttpUrl {
237237
///
238238
/// Returns `nil` if a `HttpUrl` cannot be formed with the `URL` (for example, if the string contains characters that are illegal in a URL, or is an empty string).
239239
public init?(url: URL) {
240-
guard
241-
let components = URLComponents(
242-
url: url,
243-
resolvingAgainstBaseURL: true
244-
)
245-
else { return nil }
246-
var path = components.path.trimmingCharacters(
247-
in: CharacterSet(charactersIn: "/")
248-
).components(separatedBy: "/")
240+
guard let components = URLComponents(
241+
url: url,
242+
resolvingAgainstBaseURL: true
243+
) else { return nil }
244+
245+
var path = components.path
246+
.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
247+
.components(separatedBy: "/")
248+
.filter { !$0.isEmpty }
249249
let resource: String?
250250
if path.last?.contains(".") == true {
251251
resource = path.removeLast()
252-
}
253-
else {
252+
} else {
254253
resource = nil
255254
}
256255
self.init(

Tests/SwiftHttpTests/HttpUrlTests.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,10 @@ final class HttpUrlTests: XCTestCase {
7878
"https://jsonplaceholder.typicode.com/todos?foo=bar"
7979
)
8080
}
81+
82+
func testURLInitPathIssue() throws {
83+
let url = URL(string: "https://jsonplaceholder.typicode.com")!
84+
let baseUrl = try XCTUnwrap(HttpUrl(url: url))
85+
XCTAssertEqual(baseUrl.path, [])
86+
}
8187
}

0 commit comments

Comments
 (0)