µExpress 是基于 SwiftNIO 之上的一个微型服务器框架。
它在底层的 SwiftNIO API 之上添加了一个类似 Express 的 API。
import MicroExpress
let app = Express()
app.get("/moo") { req, res, next in
res.send("Muhhh")
}
app.get("/json") { _, res, _ in
res.json([ "a": 42, "b": 1337 ])
}
app.get("/") { _, res, _ in
res.send("Homepage")
}
app.listen(1337)
此软件包是 Always Right Institute 关于 Swift Server Workgroup 的官方 Swift HTTP API 的博客系列的一部分。
请查看我们博客系列的第 3 部分来了解更多信息。这是一个小型框架。如果需要功能更全、同步的 Swift 中类似 Express 的 API,请查看 ExExpress(用于 ApacheExpress)。Noze.io 带有异步变体(但使用 Dispatch,而不是 SwiftNIO - 敬请期待)。
注意: Macro.swift 是一个功能更强大(且持续维护)的版本。
5 分钟内的 Micro Hello World(或使用下面的 swift-xcode 镜像 在 30 秒内完成)
$ mkdir MicroHelloWorld && cd MicroHelloWorld
$ swift package init --type executable
更新 Package.swift
以包含依赖项
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "MicroHelloWorld",
dependencies: [
.package(url: "https://github.com/NozeIO/MicroExpress.git",
from: "0.5.3")
],
targets: [
.target(name: "MicroHelloWorld",
dependencies: [ "MicroExpress" ])
]
)
将 main.swift
从 print("Hello World")
更改为
import MicroExpress
let app = Express()
app.get("/") { req, res, next in
res.send("Hello World")
}
app.listen(1337)
$ swift build
$ swift run
完成。通过以下方式访问:https://:1337/
使用 Xcode 11,只需打开 Package.swift
文件即可。
$ swift build
Fetching https://github.com/apple/swift-nio.git
Fetching https://github.com/AlwaysRightInstitute/mustache.git
Completed resolution in 5.97s
Cloning https://github.com/AlwaysRightInstitute/mustache.git
Resolving https://github.com/AlwaysRightInstitute/mustache.git at 0.5.9
Cloning https://github.com/apple/swift-nio.git
Resolving https://github.com/apple/swift-nio.git at 2.12.0
[100/100] Merging module MicroExpress
$ docker run --rm \
-v "${PWD}:/src" \
-v "${PWD}/.docker.build:/src/.build" \
swift:5.1.3 \
bash -c 'cd /src && swift build'
Unable to find image 'swift:5.1.3' locally
5.1.3: Pulling from library/swift
2746a4a261c9: Pull complete
...
b5d1069a5aa4: Pull complete
Digest: sha256:72d7e583452031ae88251263649fc56ea79f98f4147474080426fb5c1ff904aa
Status: Downloaded newer image for swift:5.1.3
Fetching https://github.com/apple/swift-nio.git
...
[99/99] Compiling MicroExpress Express.swift
[100/100] Merging module MicroExpress
MicroExpress 由 Helge Heß 和 ZeeZide 共同创建。我们喜欢反馈、GitHub 星星、酷炫的 合同工作,以及你能想到的任何形式的赞扬。
在 Noze.io Slack 上有一个 #microexpress
频道。欢迎加入!
(这个仍然使用 SwiftXcode 而不是 Xcode 11 SPM 支持)