Building42 / Telegraph

Secure Web Server for iOS, tvOS and macOS

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How should I format route to support multicomponent path

maxeppc opened this issue · comments

I would like to serve data when api receive call to "/first/second" but then it return 404..
How should I format route or handler to support this?

Do you want first and second to be variables?
The code fragments below are based on the Telegraph example app in this repository.

With variables

You can for example specify a route with two variables: name and country

// Example url: https://localhost:9000/hello/bob/spain
server.route(.GET, "hello/:name/:country", serverHandleHello)

Then in the handler you can grab the variable values from the request params:

private func serverHandleHello(request: HTTPRequest) -> HTTPResponse {
  let name = request.params["name"] ?? "stranger"
  let country = request.params["country"] ?? "somewhere"
  return HTTPResponse(content: "Hello \(name.capitalized) from \(country.capitalized)")
}

Without variables

If you want a route that simply consists of multiple fragments. You can do this:

// Example url: https://localhost:9000/public/countries
server.route(.GET, "public/countries", serverHandleHello)

Or if you want to allow an optional slash at the end:

// Example url: https://localhost:9000/public/countries/
server.route(.GET, "public/countries(/)", serverHandleHello)

Closing this for now, let me know if you have any questions