vapor swift server
vapor 是使用swift编写的 webframwork,适用于macOS和Ubuntu,是一个能够提供简洁,高效的web server库
Getting Started
通过Vapor Toolbox安装brew install vapor/tap/vapor
// 通过vapor-cli 创建 hello 工程
vapor new hello
cd Hello
// open xcode
vapor xcode
// runing
// Server starting on http://localhost:8080
vapor build
vapor run
通过 SPM 构建
import PackageDescription
let package = Package(
name: "VaporApp",
dependencies: [ ... ],
targets: [
.target(name: "App", dependencies: ["Vapor"]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"]),
]
)
json文件配置
// severs.json 配置网络端口
{
"http": {
"host": "0.0.0.0", // 主机地址
"port": 80 // 端口 设置为80 则不需要在API 后面跟上端口
}
}
// mysql.json
{
"hostname": "127.0.0.1",
"user": "",
"password": "",
"database": "",
"encoding": "utf8mb4",
"port": "3306"
}
示例
App 分为 Controllers 和 Models 层
启动文件 mian.swift
import App
try app(.detect()).run()
app.swift 文件是整个App的配置文件
包括Config,Environment,Services的配置,和Application的启动
public func app(_ env: Environment) throws -> Application {
var config = Config.default()
var env = env
var services = Services.default()
try configure(&config, &env, &services)
let app = try Application(config: config, environment: env, services: services)
try boot(app)
return app
}
通过Controller来进行相关的逻辑处理,然后通过router进行配置
// TodoController
final class TodoController {
/// Returns a list of all `Todo`s.
func index(_ req: Request) throws -> Future<[Todo]> {
return Todo.query(on: req).all()
}
/// Saves a decoded `Todo` to the database.
func create(_ req: Request) throws -> Future {
return try req.content.decode(Todo.self).flatMap { todo in
return todo.save(on: req)
}
}
}
// Todo Model orm
final class Todo: SQLiteModel {
var id: Int?
var title: String
init(id: Int? = nil, title: String) {
self.id = id
self.title = title
}
}
router 规则
public func routes(_ router: Router) throws {
// Controller 初始化
let todoController = TodoController()
// 创建表
router.post("todos", use: todoController.create)
// 删除
router.delete("todos", Todo.parameter, use: todoController.delete)
}
configure 配置项目
// 注册services的各种组件,router,middlewareConfig,Database,MigrationConfig
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
/// Register providers first
try services.register(FluentSQLiteProvider())
/// Register routes to the router
let router = EngineRouter.default()
try routes(router)
services.register(router, as: Router.self)
/// Register middleware
var middlewares = MiddlewareConfig() // Create _empty_ middleware config
/// middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
services.register(middlewares)
// Configure a SQLite database
let sqlite = try SQLiteDatabase(storage: .memory)
/// Register the configured SQLite database to the database config.
var databases = DatabasesConfig()
databases.add(database: sqlite, as: .sqlite)
services.register(databases)
/// Configure migrations
var migrations = MigrationConfig()
migrations.add(model: Todo.self, database: .sqlite)
services.register(migrations)
}
Provider 提供者
// 创建自定义Provider
public final class MyProvider:Provider {
public func boot(_ worker: Container) throws {}
public func didBoot(_ worker: Container) throws -> Future {
return .done(on: worker)
}
public func register(_ services: inout Services) throws {
services.register(MyClient.self)
}
}