Skip to content

Commit e2d170f

Browse files
authored
Merge pull request #3 from BinaryBirds/feature/trailingSlash
Implemented possibility to disable trailing slashes
2 parents d7faeaf + 7e8b235 commit e2d170f

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

Sources/SwiftHttp/HttpUrl.swift

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ public struct HttpUrl {
3131
/// Fragment of the url, e.g. `#foo`
3232
public private(set) var fragment: String?
3333

34+
/// Appends trailing slash at the end of the path, e.g. `localhost.com/any/path/`
35+
public private(set) var isTrailingSlashEnabled: Bool
36+
3437
///
3538
/// Initialize a HttpUrl object
3639
///
@@ -41,21 +44,24 @@ public struct HttpUrl {
4144
/// - Parameter resource: The resource, default: `nil`
4245
/// - Parameter query: The query, default: `[:]`
4346
/// - Parameter fragment: The fragment, default: `nil`
47+
/// - Parameter trailingSlashEnabled: Sets ``HttpUrl/isTrailingSlashEnabled``, default: `true`
4448
///
4549
public init(scheme: String = "https",
4650
host: String,
4751
port: Int = 80,
4852
path: [String] = [],
4953
resource: String? = nil,
5054
query: [String : String] = [:],
51-
fragment: String? = nil) {
55+
fragment: String? = nil,
56+
trailingSlashEnabled: Bool = true) {
5257
self.scheme = scheme
5358
self.host = host
5459
self.port = port
5560
self.path = path
5661
self.resource = resource
5762
self.query = query
5863
self.fragment = fragment
64+
self.isTrailingSlashEnabled = trailingSlashEnabled
5965
}
6066
}
6167

@@ -139,7 +145,9 @@ public extension HttpUrl {
139145
path += (resource.hasPrefix("/") ? resource : "/" + resource)
140146
}
141147
else {
142-
path += "/"
148+
if isTrailingSlashEnabled {
149+
path += "/"
150+
}
143151
}
144152
components.path = path
145153
components.fragment = fragment

Tests/SwiftHttpTests/HttpUrlTests.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,15 @@ final class HttpUrlTests: XCTestCase {
2727
])
2828
XCTAssertEqual(query2Url.url.absoluteString, "https://jsonplaceholder.typicode.com/todos/?foo=1")
2929
}
30+
31+
func testTrailingSlash() {
32+
let baseUrl = HttpUrl(host: "jsonplaceholder.typicode.com", trailingSlashEnabled: false)
33+
34+
let todosUrl = baseUrl.path("todos")
35+
XCTAssertEqual(todosUrl.url.absoluteString, "https://jsonplaceholder.typicode.com/todos")
36+
37+
let query1Url = baseUrl.path("todos").query("foo", "bar")
38+
XCTAssertEqual(query1Url.url.absoluteString, "https://jsonplaceholder.typicode.com/todos?foo=bar")
39+
}
3040
}
3141

0 commit comments

Comments
 (0)