Vapor:基于Swift的类似于Laravel的服务端框架
Quick StartInstalling Swift好像最新的OSX系统是自带Swift的,不过笔者本机的版本是2.1.1,而Vapor的要求是2.2以上版本,因此还是要来Swift.org官网来更新一波的。 首先需要在这嘎达下载下安装文件,然后进行配置。 OSX默认的OSX系统上的Swift安装的地址为: $ export PATH=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin:"${PATH}" Linux首先需要安装下 $ sudo apt-get install clang 如果没有把Swift的工具链安装在系统根目录下,可以使用如下方式来讲Swift可执行命令设置为全局可用: $ export PATH=/path/to/Swift/usr/bin:"${PATH}" 可以使用 $ swift --version HelloWorld最简单的基于Vapor的架构就是如下 `
` 其中Package.swift的内容如下: import PackageDescription let package = Package( name: "VaporApp",dependencies: [ .Package(url: "https://github.com/qutheory/vapor.git",majorVersion: 0),.Package(url: "https://github.com/qutheory/vapor-stencil.git",majorVersion: 0) ] ) 而main.swift的内容为: import Vapor let server = Server() server.run() 使用 Server has started on port 80 Clonesudo apt-get install git git clone git@github.com:qutheory/vapor-example.git Compilecd vapor-example swift build --configuration release Automatic Startup如果需要整改网站自启动,则需要将如下配置放置到init目录下,/etc/init/vapor-example.conf description "Vapor Example" start on startup exec /home/<USERNAME>/vapor-example/.build/release/VaporApp --port=80 --workDir=/home/<USERNAME>/vapor-example 这样已经可以执行自启动了: sudo start vapor-example API OverviewServer如果需要创建一个服务器:
import Vapor let server = Server() server.run() 也可以自定义需要启动的端口 server.run(port: 8080) 如果有时候端口不能监听,请确定你的端口是处于开启状态,可以使用 RoutingVapor中的路由返回跟Lavarel中非常类似:
Route.get("welcome") { request in return "Hello" } //...start server 这样所有关于 JSON返回JSON数据 Route.get("version") { request in return ["version": "1.0"] } 所有对于 Views也可以返回HTML界面 Route.get("/") { request in return View(path: "index.html") } 或者使用Stencil Stencil 模板。 <html> <h1>{{ message }}</h1> </html> Route.get("/") { request in return View(path: "index.stencil",context: ["message": "Hello"]) } 如果添加了 Stencil如果需要添加
.Package(url: "https://github.com/qutheory/vapor-stencil.git",majorVersion: 0) Then set the
import VaporStencil //set the stencil renderer //for all .stencil files View.renderers[".stencil"] = StencilRenderer() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |