路由、中间件、Auth用户权限。
这个本来需要分开写的但是,本人并没有理解透、所以这里就贴一些官方文档。以后可能会更新。如果有感觉自己写的好的我可以再这里添链接。
路由 Routing
基础路由
Routing is one of the most critical parts of a web framework. The router decides which requests get which responses.
路由是Web框架中最重要的部分之一。 路由器决定哪些请求得到哪些响应。
Vapor has a plethora of functionality for routing including route builders, groups, and collections. In this section, we will look at the basics of routing.
Vapor具有很多的路由功能,包括路由builders,组和集合。 在本节中,我们将看看路由的基础知识。
注册
drop.get("welcome") { request in
return "Hello"
}
嵌套、多重路由
drop.get("foo", "bar", "baz") { request in
return "You requested /foo/bar/baz"
}
重定向
drop.get("vapor") { request in
return Response(redirect: "http://vapor.codes")
}
响应类型(Response Representable)
drop.get("json") { request in
var json = JSON()
try json.set("number", 123)
try json.set("text", "unicorns")
try json.set("bool", false)
return json
}
响应失败
drop.get("404") { request in
throw Abort(.notFound)
}
drop.get("error") { request in
throw Abort(.badRequest, reason: "Sorry 😱")
}
Fallback
app.get("anything", "*") { request in
return "Matches anything after /anything"
}
Fallback routes allow you to match multiple layers of nesting slashes.
回退路线允许您匹配多个嵌套斜杠层。
For example, the above route matches all of the following and more:
例如,上面的路线匹配以下所有内容:
/anything
/anything/foo
/anything/foo/bar
/anything/foo/bar/baz
参数 Routing Parameters
This creates a route that matches
users/:id
where the:id
is anInt
. Here's what it would look like using manual route parameters.这将创建一个匹配
users /:id
的路由:id
是一个Int
。 这是使用手动路由参数的样子。
drop.get("users", ":id") { request in
guard let userId = request.parameters["id"]?.int else {
throw Abort.badRequest
}
return "You requested User #\(userId)"
}
Parameterizable(可参数化的)
- Any type conforming to Parameterizable can be used as a parameter. By default, all Vapor Models conform.
- 大致就是能直接获得一个Model对象
drop.get("users", User.parameter) { req in
let user = try req.parameters.next(User.self)
return "You requested \(user.name)"
}
Route Groups (路由组)
Group
drop.group("v1") { v1 in
v1.get("users") { request in
// get the users
}
}
Grouped
let v1 = drop.grouped("v1")
v1.get("users") { request in
// get the users
}
Middleware (中间件)
drop.group(AuthMiddleware()) { authorized in
authorized.get("token") { request in
// has been authorized
}
}
Host
drop.group(host: "vapor.codes") { vapor in
vapor.get { request in
// only responds to requests to vapor.codes
}
}
Chaining 链式调用
drop.grouped(host: "vapor.codes").grouped(AuthMiddleware()).group("v1") { authedSecureV1 in
// add routes here
}
Route Collections
Route collections allow multiple routes and route groups to be organized in different files or modules.
路由集合允许将多个路由和路由组组织在不同的文件或模块中。
Example
import Vapor
import HTTP
import Routing
class V1Collection: RouteCollection {
func build(_ builder: RouteBuilder) {
let v1 = builder.grouped("v1")
let users = v1.grouped("users")
let articles = v1.grouped("articles")
users.get { request in
return "Requested all users."
}
articles.get(Article.init) { request, article in
return "Requested \(article.name)"
}
}
}
- 调用如下
let v1 = V1Collection()
drop.collection(v1)
Empty Initializable
- You can add EmptyInitializable to your route collection if it has an empty init method. This will allow you to add the route collection via its type name.
class V1Collection: RouteCollection, EmptyInitializable {
init() { }
...
- 现在我们可以这样初始化进行调用
drop.collection(V1Collection.self)
中间件 Middleware
https://docs.vapor.codes/2.0/http/middleware/
Middleware
Middleware is an essential part of any modern web framework. It allows you to modify requests and responses as they pass between the client and your server.
中间件是任何现代Web框架的重要组成部分。 它允许您在客户端和服务器之间传递请求和响应。
You can imagine middleware as a chain of logic connecting your server to the client requesting your web app.
您可以将中间件想象为连接您的服务器和请求您的Web应用程序的客户端的逻辑链。
Version Middleware
As an example, let's create a middleware that will add the version of our API to each response. The middleware would look something like this:
作为一个例子,我们来创建一个中间件,将我们的API版本添加到每个响应中。 中间件看起来像这样:
import HTTP
final class VersionMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let response = try next.respond(to: request)
response.headers["Version"] = "API v1.0"
return response
}
}
- 使用的话大致如下
import Vapor
let config = try Config()
config.addConfigurable(middleware: VersionMiddleware(), name: "version")
let drop = try Droplet(config)
Auth用户认证 HTTP Session Validation Auth
HTTP https://docs.vapor.codes/2.0/http/package/
这一节是Web服务器的核心、比如响应头、认证、跨域、Session等等。
ResponseRepresentable https://docs.vapor.codes/2.0/http/response-representable/
Auth https://docs.vapor.codes/2.0/auth/package/
- 使用Auth
import PackageDescription
let package = Package(
name: "Project",
dependencies: [
.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2),
.Package(url: "https://github.com/vapor/auth-provider.git", majorVersion: 1)
],
exclude: [ ... ]
)
对于持久化认证
1、需要 SessionPersistable
let memory = MemorySessions()
let sessionsMiddleware = SessionsMiddleware(memory)
2、 需要 Persist
let persistMiddleware = PersistMiddleware(User.self)
- Authentication
let passwordMiddleware = PasswordAuthenticationMiddleware(User.self)
- Droplet
import Vapor
import Sessions
import AuthProvider
let drop = try Droplet()
let authed = drop.grouped([sessionsMiddleware, persistMiddleware, passwordMiddleware])
- 返回已经认证的用户
authed.get("me") { req in
// return the authenticated user
return try req.auth.assertAuthenticated(User.self)
}