2

In building an app with PerfectHTTP I've come up against a problem with routing: Routes that are used as intermediate routes cannot also be used as final routes.

When set up as below, some URLs track correctly (/index.html in the example), while some URLs do not (/ in the example).

Is there some special sauce I'm missing here, or is what I'm trying to do simply impossible using Perfect?

import PerfectHTTP
import PerfectHTTPServer

// This does various housekeeping to set things common to all requests.
var routes = Routes() {
  request, response in

  Log.info(message: "\(request.method) \(request.uri)")
  response
    .setHeader(.contentType, value: "text/plain")
    .next()
}

// For this handler, http://localhost:8181/index.html works,
// but http://localhost:8181/ does not
routes.add(method: .get, uris: ["/", "index.html"]) {
  request, response in
  response
    .appendBody(string: "Hello, world!")
    .completed()
}

HTTPServer.launch(.server(name: "localhost", port: 8181, routes: [routes]))
Williham Totland
  • 28,471
  • 6
  • 52
  • 68

1 Answers1

0

if you want set things common to all requests. use filter.

my routes is working

see more https://perfect.org/docs/filters.html

var routes = Routes()
routes.add(method: .get, uris: ["/", "index.html"]) {
  request, response in
  response
    .appendBody(string: "Hello, world!")
    .completed()
}

struct MyFilter: HTTPRequestFilter {
    func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
        print("request method: \(request.method)")
        callback(.continue(request, response))
    }
}

do {
    let server = HTTPServer()
    server.serverName = "testServer"
    server.serverPort = 8181
    server.addRoutes(routes)
    server.setRequestFilters([(MyFilter(), HTTPFilterPriority.high)])
    try server.start()
} catch {
    fatalError("\(error)") // fatal error launching one of the servers
}
Elijah
  • 1
  • 1