Vapor 第二篇 启动
in 技术 with 0 comment

Vapor 第二篇 启动

in 技术 with 0 comment

前言

我们来看看 Vapor 项目是如何初始化,加载配置,并启动起来的。

结构图

Sn_2018-08-21_11-37-45_content.png

绿色边框表示 protocol,紫色边框表示 struct 或 class

main.swift

try app(.detect()).run()

启动的入口是 main.swift 文件,并且只有上面一行代码。

为什么是 main.swift,如果你把代码放到其它的 .swift 文件中,则会报错。下面是官文文档的一段摘要:

You’ll notice that earlier we said top-level code isn’t allowed in most of your app’s source files. The exception is a special file named “main.swift”, which behaves much like a playground file, but is built with your app’s source code. 

默认值

下面参数都是项目中初始化 Application 对象的默认值。

Services

如果要了解启动流程的话,那么 Services+Default.swift 中的两个注册的 Service 需要着重介绍:

services.register { container -> CommandConfig in
    return .default()
}
services.register { container -> Commands in
    return try container.make(CommandConfig.self).resolve(for: container)
}

CommandConfig

config.use(ServeCommand.self, as: "serve", isDefault: true)
config.use(RoutesCommand.self, as: "routes")
config.use(BootCommand.self, as: "boot")

上面是 CommandConfig+Default.swift 中的代码。解释了命令 .build/debug/Run serveisDefault: true 参数标明了默认可以不写,因为 serve 被标记为默认执行的 Command。

Commands

第二个注册方法做了两件事情:

  1. 通过第一个 register 方法获得 CommandConfig 对象;
  2. 利用 CommandConfig 配置的三个 Command 初始化 Commands 对象。

Run

列出 run 方法主要做的几件事情:

  1. 通过注册的 Commands 对象获得默认执行的 Command - serve;
  2. 解析 environment.commandInput 的命令行参数;
  3. 向控制台输出将要执行的命令行;
  4. 通过获得的参数中的 hostname 和 port,调用 NIOServer 的 start 方法。

后续还需要更多信息,就涉及到 Apple 开源的网路应用程序开发框架 SwiftNIO 了。后续我也会写关于它的文章,敬请期待。

Responses