【问题标题】:Making a route both intermediate and final?制作中间路线和最终路线?
【发布时间】:2019-11-07 12:38:13
【问题描述】:

在使用PerfectHTTP 构建应用程序时,我遇到了路由问题:用作中间路由的路由也不能用作最终路由。

当设置如下时,某些 URL 正确跟踪(示例中为 /index.html),而某些 URL 不正确(示例中为 /)。

我在这里缺少一些特殊的酱汁吗,或者我试图用 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]))

【问题讨论】:

    标签: swift url-routing perfect


    【解决方案1】:

    如果你想为所有请求设置通用的东西。使用过滤器。

    我的路线正在运行

    查看更多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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 2016-01-22
      • 2011-10-19
      • 1970-01-01
      相关资源
      最近更新 更多