Swift国内社区: SwiftMic
Middleware 是现代 Web 框架中必不可少的一部分。通过 Middleware 可以单独处理 Request 和 Response,极其方便。
基本用法
SampleMiddleware.swift
import Vapor
import HTTP
class SampleMiddleware: Middleware {
func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
// You can manipulate the request before calling the handler
// and abort early if necessary, a good injection point for
// handling auth.
// 此处可统一处理 Request 请求
let response = try chain.respond(to: request)
// 此处可统一处理 Response 响应
// You can also manipulate the response to add headers
// cookies, etc.
return response
// Vapor Middleware is based on S4 Middleware.
// This means you can share it with any other project
// that uses S4 Middleware.
}
}
main.swift
drop.middleware.append(SampleMiddleware())
每次 Request 和 Response 都将会响应到 SampleMiddleware 中的 respond 方法。
示例1
如果想给所有 API 的 Response 增加一个版本号字段,可直接在 SampleMiddleware
中添加代码: response.headers["Api_Version"] = "v1"
即可,而无需在每个 Response 中进行设置。
import Vapor
import HTTP
class SampleMiddleware: Middleware {
func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
let response = try chain.respond(to: request)
response.headers["Api_Version"] = "v1"
return response
}
}
示例2
有些 API 需要登录后才能调用,这里涉及到用户鉴权的问题,可通过 Middleware 统一处理 token 异常情况,而无需在每个 Response 中处理。
定义异常类型
enum ZException: Error {
case ERROR_AUTH_TOKEN_INVALID
}
ERROR_AUTH_TOKEN_INVALID
异常类型统一处理
import Vapor
import HTTP
class SampleMiddleware: Middleware {
func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
do {
return try chain.respond(to: request)
} catch ZException.ERROR_AUTH_TOKEN_INVALID {
throw Abort.custom(status: .unauthorized, message: "ERROR_AUTH_TOKEN_INVALID")
}
}
}
当检测到 token 无效时,只需要抛出 ERROR_AUTH_TOKEN_INVALID 异常即可。
throw ZException.ERROR_AUTH_TOKEN_INVALID
Go to Vapor系列教程 - 目录