Swift国内社区: SwiftMic
Droplet
是一个比较综合的类,它负责路由的注册、服务的启动和中间件的添加等等。
初始化
编辑 main.swift
import Vapor
let drop = Droplet()
drop.serve()
使用默认参数配置的 Droplet 就被构造出来了。
同时,也可以自定义构造 Droplet
public init(
// non-providable
arguments: [String]? = nil,
workDir workDirProvided: String? = nil,
config configProvided: Config? = nil,
localization localizationProvided: Localization? = nil,
// providable
server: ServerProtocol.Type? = nil,
sessions: Sessions? = nil,
hash: Hash? = nil,
console: ConsoleProtocol? = nil,
log: Log? = nil,
client: ClientProtocol.Type? = nil,
database: Database? = nil,
// database preparations
preparations: [Preparation.Type] = [],
// providers
providers providerTypes: [Provider.Type] = [],
initializedProviders: [Provider] = []
)
环境
定义
Environment
是一个枚举类型,具体定义如下
/**
Represents the current environment the
droplet is running in. This information
can be used to conditionally show debug or testing information.
*/
public enum Environment: Equatable {
case production
case test
case development
case custom(String)
init(id string: String) {
switch string.lowercased() {
case "production", "prod":
self = .production
case "test":
self = .test
case "development", "dev":
self = .development
default:
self = .custom(string)
}
}
}
分为 production
、 test
、development
和 custom
环境类型。
使用
let env = drop.config.environment
if .production == env {
print("environment = production")
} else if .test == env {
print("environment = test")
} else if .development == env {
print("environment = development")
} else {
print("environment = \(env)")
}
可通过执行如下命令来指定当前环境类型
- production
vapor run serve --env=production
或
vapor run serve --env=prod
输出
environment = production
- test
vapor run serve --env=test
输出
environment = test
- development
vapor run serve --env=development
或
vapor run serve --env=dev
输出
environment = development
- ** custom**
vapor run serve --env=myenv
输出
environment = myenv
其中, myenv
也可以是其它任意字符串。
注意:
- 如果未明确指定环境的话,默认将以
development
环境执行。 -
production
环境下可以过滤 Debug 日志以提高性能,建议最终部署的时候选择production
环境。
工作目录
可通过 drop.workDir
获取当前工作目录。
print("workDir = \(drop.workDir)")
输出
workDir = /Users/Cary/Documents/Swift/Vapor/Project/vapor_test/
注意: 输出的路径由执行时所在路径决定。
Go to Vapor系列教程 - 目录