Vapor 的一些基本用法,包括两种 GET 请求,两种 POST 请求及自定义中间件。
router.get("getName", use: getNameHandler)
func getNameHandler(_ req: Request) throws -> [String:String] {
guard let name = req.query[String.self, at: "name"] else {
return ["status":"-1","message": "缺少 name 参数"]
}
return ["status":"0","message":"Hello,\(name) !"]
}
http://localhost:8080/getName?name=Jinxiansen
{
"status": "0",
"message": "Hello, Jinxiansen !"
}
router.get("getName2", String.parameter) { req -> [String:String] in
let name = try req.parameters.next(String.self)
return ["status":"0","message":"Hello,\(name) !"]
}
http://localhost:8080/getName/Jinxiansen
{
"status": "0",
"message": "Hello,Jinxiansen"
}
需要声明 Struct:
struct UserContainer: Content {
var name: String
var age: Int?
}
router.post("post1UserInfo", use: post1UserInfoHandler)
func post1UserInfoHandler(_ req: Request) throws -> Future<[String:String]> {
return try req.content.decode(UserContainer.self).map({ container in
let age = container.age ?? 0
let result = ["status":"0","message":"Hello,\(container.name) !","age": age.description]
return result
}
URL :http://localhost:8080/getName POST 请求的 Body 中添加 Name 字段及其值,发送请求即可。
{
"status": "0",
"message": "Hello,3ks !"
}
同样需要声明 Struct:
struct UserContainer: Content {
var name: String
var age: Int? //当类型后加 ? 的时候,请求参数时为可选。
}
router.post(UserContainer.self, at: "post2UserInfo", use: post2UserInfoHandler)
func post2UserInfoHandler(_ req: Request,container: UserContainer) throws -> Future<[String:String]> {
let age = container.age ?? 0
let result = ["status":"0","message":"Hello,\(container.name) !","age": age.description]
return req.eventLoop.newSucceededFuture(result: result)
}
同上。
{
"status": "0",
"message": "Hello,3ks !"
}
自定义中间件,需要继承于 Middleware
,并实现下面这个方法:
func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response>
在方法体中做出判断并拦截处理。
比如要自定义404
状态,系统默认返回的是 String
Not found,
我们如果要返回为 JSON
,
可以这样实现这个方法:
public func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
return try next.respond(to: request).flatMap({ (resp) in
let status = resp.http.status
if status == .notFound { //拦截 404,block回调处理。
if let resp = try self.closure(request) {
return resp
}
}
return request.eventLoop.newSucceededFuture(result: resp)
})
}
调用:
middlewares.use(ExceptionMiddleware(closure: { (req) -> (EventLoopFuture<Response>?) in
let dict = ["status":"404","message":"访问路径不存在"]
return try dict.encode(for: req)
}))
这里其实任意对象都可以转为 Response ,所以你可以在这里自定义返回1张图片、1个网页、或其他数据类型。
详情见 ExceptionMiddleware 。
亦如上,需要继承于 Middleware
,并实现下面这个方法:
func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response>
代码量相对稍多,见 GuardianMiddleware 。
未完,待续...