【发布时间】:2017-02-14 06:22:29
【问题描述】:
我已经创建了 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 中进行配置吗?
【问题讨论】: