Titan 是一个可扩展、强大且易于使用的微框架,适用于 服务端 Swift。
以一种便捷的方式,在 Linux 或 Docker 下编写和运行 生产环境的 Web 应用 & 服务。
Swift 3 已不再支持,但可以在 0.7.x 的标签下找到。
以下示例具有以下功能
Package.swift:
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "mywebapp",
products: [
.executable(name: "mywebapp", targets: ["mywebapp"]),
],
dependencies: [
.package(url: "https://github.com/bermudadigitalstudio/TitanKituraAdapter.git", .upToNextMinor(from: "0.9.0")),
.package(url: "https://github.com/bermudadigitalstudio/Titan", .upToNextMinor(from: "0.9.0"))
],
targets: [
.target(
name: "mywebapp",
dependencies: [
"TitanKituraAdapter",
"Titan"
]),
]
)
main.swift:
import Titan
import TitanKituraAdapter
let app = Titan()
/// The Response is set to 404 by default.
/// if no subsequent routing function is called, a 404 will be returned
app.addFunction(DefaultTo404)
/// Hello World, req is sent to next matching route
app.get("/") { req, _ in
return (req, Response(200, "Hello World")) // here we "overwrite" the 404 that was returned in the previous func.
}
/// 2 parameters in URL
app.delete("/item/{item_id}/subitem/{sub_item_id}") { req, res, paramaters in
let itemId = params["item_id"] ?? ""
let subId = params["sub_item_id"] ?? ""
let text = "I will delete \(subId) in \(itemId)"
return(req, Response(200, text))
}
/// parse JSON sent via POST, return 400 on parsing error
app.post("/data") { req, _ in
guard let json = req.json as? [String: Any] else {
return (req, Response(400))
}
return(req, Response(200, "I received \(json)"))
}
/// let’s manipulate the response of all GET routes
/// and yes, that is already a simple example for a middleware!
app.get("*") { req, res in
var newRes = res.copy() // res is a constant, so we need to copy
newRes.body += " and hello from the middleware!"
return (req, newRes) // will return "Hello World and hello from the middleware!"
}
// start the Kitura webserver on port 8000
TitanKituraAdapter.serve(app.app, on: 8000)
现在您可以运行 Web 服务器并打开 https://:8000 或 https://:8000/item/foo/subitem/bar,或者通过 POST 将 JSON 发送到 https://:8000/data
Function
s 并直接测试它们来编写单元测试。执行 Scripts/test.sh
以在 Docker 容器内运行所有单元测试。
Titan 由 Thomas Catterall (@swizzlr), Johannes Erhardt (@johanneserhardt), Sebastian Kreutzberger (@skreutzberger), Laurent Gaches (@lgaches), 和 Ryan Collins (@rymcol) 维护。
非常欢迎贡献。您可以处理现有的 Github 问题,或者在一个新的 Github 问题中与我们讨论您的想法。谢谢 🙌
Titan 最初是在与 Bermuda Digital Studio (BDS) 德国合作的项目中开发的。BDS 团队致力于为可再生能源公司 innogy SE 的零售业务实现数字化产品管理、设计和开发。目标是数字化和颠覆能源。
Titan Framework 在 Apache 2.0 License 下发布。