Swift國內社區: SwiftMic
Middleware 是現代 Web 框架中必不可少的一部分。通過 Middleware 可以單獨處理 Request 和 Response,極其方便。
Middleware
基本用法
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系列教程 - 目錄