|
13 | 13 | - [Usage](#usage)
|
14 | 14 | - [Handlers](#handlers)
|
15 | 15 | - [Routes](#routes)
|
| 16 | + - [Route Parameters](#route-parameters) |
16 | 17 | - [Macros](#preview-macro-handler)
|
17 | 18 | - [WebSockets](#websockets)
|
18 | 19 | - [FlyingSocks](#flyingsocks)
|
@@ -213,6 +214,14 @@ route ~= HTTPRequest(method: .GET, path: "/hello/dog/world") // true
|
213 | 214 | route ~= HTTPRequest(method: .GET, path: "/hello/fish/sea") // false
|
214 | 215 | ```
|
215 | 216 |
|
| 217 | +Routes can include [parameters](#route-parameters) that match like wildcards allowing handlers to extract the value from the request. |
| 218 | + |
| 219 | +```swift |
| 220 | +let route = HTTPRoute("GET /hello/:beast/world") |
| 221 | + |
| 222 | +let beast = request.routeParameters["beast"] |
| 223 | +``` |
| 224 | + |
216 | 225 | Trailing wildcards match all trailing path components:
|
217 | 226 |
|
218 | 227 | ```swift
|
@@ -280,6 +289,41 @@ let route = HTTPRoute("POST *", body: .json(where: "food == 'fish'"))
|
280 | 289 | {"side": "chips", "food": "fish"}
|
281 | 290 | ```
|
282 | 291 |
|
| 292 | +## Route Parameters |
| 293 | + |
| 294 | +Routes can include named parameters within a path or query item using the `:` prefix. Any string supplied to this parameter will match the route, handlers can access the value of the string using `request.routePamaters`. |
| 295 | + |
| 296 | +```swift |
| 297 | +handler.appendRoute("GET /creature/:name?type=:beast") { request in |
| 298 | + let name = request.routeParameters["name"] |
| 299 | + let beast = request.routeParameters["beast"] |
| 300 | + return HTTPResponse(statusCode: .ok) |
| 301 | +} |
| 302 | +``` |
| 303 | + |
| 304 | +When using Swift 5.9+, route parameters can be automatically extracted and mapped to closure parameters of handlers. |
| 305 | + |
| 306 | +```swift |
| 307 | +enum Beast: String, HTTPRouteParameterValue { |
| 308 | + case fish |
| 309 | + case dog |
| 310 | +} |
| 311 | + |
| 312 | +handler.appendRoute("GET /creature/:name?type=:beast") { (name: String, beast: Beast) -> HTTPResponse in |
| 313 | + return HTTPResponse(statusCode: .ok) |
| 314 | +} |
| 315 | +``` |
| 316 | + |
| 317 | +The request can be optionally included. |
| 318 | + |
| 319 | +```swift |
| 320 | +handler.appendRoute("GET /creature/:name?type=:beast") { (request: HTTPRequest, name: String, beast: Beast) -> HTTPResponse in |
| 321 | + return HTTPResponse(statusCode: .ok) |
| 322 | +} |
| 323 | +``` |
| 324 | + |
| 325 | +`String`, `Int`, `Double`, `Bool` and any type that conforms to `HTTPRouteParameterValue` can be extracted. |
| 326 | + |
283 | 327 | ## WebSockets
|
284 | 328 | `HTTPResponse` can switch the connection to the [WebSocket](https://datatracker.ietf.org/doc/html/rfc6455) protocol by provding a `WSHandler` within the response payload.
|
285 | 329 |
|
|
0 commit comments