Skip to content

Route Parameters

Compare
Choose a tag to compare
@swhitty swhitty released this 13 Jul 23:46
· 131 commits to main since this release
b37b5ab
  • Adds route parameters (🙏🏻 @tonyarnold)
  • HTTPRoute now matches methods against Set<HTTPMethod>
  • Replaces AsyncChunkedSequence with AsyncBufferedSequence
  • Support for Transfer-Encoding: chunked for responses without a known size

Route Parameters

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.

handler.appendRoute("GET /creature/:name?type=:beast") { request in
  let name = request.routeParameters["name"]
  let beast = request.routeParameters["beast"]
  return HTTPResponse(statusCode: .ok)
}

When using Swift 5.9+, route parameters can be automatically extracted and mapped to closure parameters of handlers.

enum Beast: String, HTTPRouteParameterValue {
  case fish
  case dog
}

handler.appendRoute("GET /creature/:name?type=:beast") { (name: String, beast: Beast) -> HTTPResponse in
  return HTTPResponse(statusCode: .ok)
}

The request can be optionally included.

handler.appendRoute("GET /creature/:name?type=:beast") { (request: HTTPRequest, name: String, beast: Beast) -> HTTPResponse in
  return HTTPResponse(statusCode: .ok)
}

String, Int, Double, Bool and any type that conforms to HTTPRouteParameterValue can be extracted.