swift + vapor写服务器

参考文章

示例demo

vapor

看了参考文章写的用swift写服务器,自己跟着做了一遍,踩了不少坑,于是记录成文:

下载安装swift开发版的snapshot

swift官网

此处有坑,不要下载最新的3.16号的安装包,要下载和vapor使用版本一致的包,可打开vapor里的.swift-version文件查看其使用版本,目前使用的是:
https://swift.org/builds/development/xcode/swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a/swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a-osx.pkg

添加环境变量

若使用的是Xcode7.3:export TOOLCHAINS=swift

或者使用Xcode7.2:PATH=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin:$PATH

添加后执行:swift --version,确认显示为:Apple Swift version 3.0-dev

再执行:swift build --version,确认显示为:Apple Swift Package Manager 0.1

若出现以下错误(下载DEVELOPMENT-SNAPSHOT-2016-03-16-a的包会出这个问题,我最初下载的3.16的包,遇到这个问题,一并记录在这儿;下载安装3.1的包不会有该问题):

dyld: Library not loaded: @rpath/libswiftCore.dylib
Referenced from: /Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2016-03-16-a.xctoolchain/usr/bin/swift-build
Reason: image not found

解决办法,添加环境变量:
export DYLD_LIBRARY_PATH=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/lib/swift/macosx:$DYLD_LIBRARY_PATH

Package.swift

示例项目里的package url要改为:https://github.com/qutheory/vapor.git

build settings里设置import paths

示例项目已设置好,若是自己新建项目,需要自己设置

$(SRCROOT)/.build/debug
$(SRCROOT)/.build/release

toolchain运行Xcode

xcrun launch-with-toolchain /Library/Developer/Toolchains/swift-latest.xctoolchain

或者Xcode7.3可直接选择toolchain为development snapshot运行起来

修改main.swift代码

示例项目的代码编译出错,看了下vapor的使用示例,我改成了如下代码:

import Foundation
import Vapor

let app = Application()

app.get("hello") { _ in
    if let json = try? Json(["Hello" : "World"]) {
        return json
    }

    return "hello swift world"
}

app.get("hello/:name") { request in
    let name = request.parameters["name"] ?? "World"

    if let json = try? Json(["Hello" : name]) {
        return json
    }

    return "Hello: \(name)"
}

app.start(port: 8080)

在示例项目路径下执行如下指令启动服务器:

swift build && .build/debug/SwiftServerIO

浏览器输入:http://localhost:8080/hello,或http://localhost:8080/hello/ray,可看到显示的服务器返回数据

上传Heroku

先注册帐号并创建一个app:https://id.heroku.com/login

注:示例项目已经包括了buildpack文件。其内容作用为:告诉Heroku去运行SwiftServerIO可执行文件。没有该文件的话需要自己创建并git提交上传

还要在项目目录下创建.swift-version文件:
touch .swift-version

输入内容:DEVELOPMENT-SNAPSHOT-2016-03-01-a

安装Heroku Toolbelt

下载地址

安装好以后执行以下命令(heroku git指令执行需翻墙,如果项目已经是git项目,则git init不用执行):

cd swift-server-io/
git init
heroku git:remote -a 'heroku上创建的app名'

提交代码(以后可多次执行):

git add .
git commit -m "coding"
git push heroku master

执行git push会失败,解决方案:执行该命令:
heroku buildpacks:set https://github.com/kylef/heroku-buildpack-swift.git

最后一步

执行指令(只需执行一次,以后即使在其他电脑上都不需要再次执行了):
heroku ps:scale web=1

最后浏览器打开:http://ljswiftserver.herokuapp.com/hello

欢呼吧!

问题

没法debug!!!Xcode编译项目会报错,只能通过命令行运行程序。若有大牛知道,忘不吝赐教