从中间件Vapor中排除一些视图

时间:2017-02-14 06:22:29

标签: swift vapor

我创建了Vapor项目。我已经注册了两个视图和两个API,如下所示。

    drop.get { req in
        return try drop.view.make("index.html")
    }

    drop.get("home") { req in
        return try drop.view.make("home.html")
    }

    // Register the GET request routes
    drop.get("appname") { request in
        return "Welcome to Swift Web service";
    }

    drop.get("appversion") { request in
        return "v1.0";
    }

中间件代码:

    // Added the Middleware version for request and response
    final class VersionMiddleware: Middleware {

        // Interact with request and response
        func respond(to request: Request, chainingTo next: Responder) throws -> Response {

            //Middleware is the perfect place to catch errors thrown from anywhere in the application.
            do {
                // Exclude the views from middleware
                if ( request.uri.path != "/") {
                    // The request has a 'Version' named token that equals "API \(httpVersion)"
                    guard request.headers["access_token"] == "\(publicAPIKey)" else {
                        throw Abort.custom(
                            status: .badRequest,
                            message: "Sorry, Wrong web service authendication!!"
                        ) // The request will be aborted.
                    }

                }
                let response = try next.respond(to: request)
                response.headers["Version"] = "API \(httpVersion)"
                return response
            } catch {
                throw Abort.custom(
                    status: .badRequest,
                    message: "Sorry, we were unable to query the Web service."
                )
            }
        }
    }

添加了中间件配置:

    // Configure the middleware
    drop.addConfigurable(middleware: VersionMiddleware() as Middleware, name: "VersionMiddleware")
  

我的问题是:

     

每当用户尝试加载home.html时,它应该验证中间件   条件和如果我们加载index.html服务器将排除   中间件验证。

     

与API相同:每当用户尝试加载“/ appname”时,它应该   验证中间件条件,如果我们加载“appversion”服务器将   排除中间件验证。

我使用request.uri.path!=“/”完成了这个。我们还有其他方法可以在Vapor中配置吗?

1 个答案:

答案 0 :(得分:2)

您可以group一组路由并在那里分配中间件

drop.group(VersionMiddleware()) { group in
    drop.get("home") { req in
        return try drop.view.make("home.html")
    }

    // Register the GET request routes
    drop.get("appname") { request in
        return "Welcome to Swift Web service";
    }
}

drop.get { req in
    return try drop.view.make("index.html")
}

drop.get("appversion") { request in
    return "v1.0";
}

不要调用addConfigurable方法