LoginSignup
12
14

More than 5 years have passed since last update.

SwiftのWebフレームワークのVaporでちょっと遊んでみた

Last updated at Posted at 2016-07-08

サンプル

nnsnodnb/swift-vapor-sample

サンプルを会社のLT大会のために作ったので適当にみてくださるとわかるかと思います。

環境構築

想定環境

  • MacOS X 10.11.x
  • Xcode 7.3.x
  • Swift 3.0-dev

Mac上のSwift環境を汚したくないのでSwiftenvを導入していきます。

# Homebrewが入っていない場合はここから
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

# Homebrewが入っている場合は以下から
$ brew install kylef/formulae/swiftenv
$ echo 'export SWIFTENV_ROOT="$HOME/.swiftenv"' >> ~/.bash_profile
$ echo 'export PATH="$SWIFTENV_ROOT/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(swiftenv init -)"' >> ~/.bash_profile
$ exec $SHELL
$ swiftenv --version

エラーが起きなければSwiftenvの導入は完了です。

$ swiftenv install https://swift.org/builds/development/xcode/swift-DEVELOPMENT-SNAPSHOT-2016-06-06-a/swift-DEVELOPMENT-SNAPSHOT-2016-06-06-a-osx.pkg
$ swiftenv versions
$ swiftenv global DEVELOPMENT-SNAPSHOT-2016-06-06-a

Vaporプロジェクト作成

プロジェクトフォルダ作成

$ mkdir vapor_sample
$ cd vapor_sample

プロジェクト初期化

$ swift build --init

パッケージ追加

Swift Package Managerを使用します。

Package.swift
import PackageDescription

let package = Package(
    name: "vapor_sample",
    dependencies: [
        // Vaporパッケージ
        .Package(url: "https://github.com/qutheory/vapor.git", majorVersion: 0, minor: 11),
        // Vapor テンプレートパッケージ
        .Package(url: "https://github.com/qutheory/vapor-mustache.git", majorVersion: 0, minor: 7)
    ]
)

HTMLファイルや動的にコンテンツを変更したいものを設置した場合はResources/Viewsフォルダを作成し設置する。
また、動的にコンテンツを変更したい場合はMustacheというものを使用します。
詳しくは公式ドキュメントを参照。hoge.mustacheという形

{{ Mustache }}

$ swift build

追加したパッケージが無事インストールされるはずです。

テンプレートを返すサンプル

main.swift
import Vapor
import VaporMustache

let mustache = VaporMustache.Provider()
let app = Application(providers: [mustache])

app.get("/") { request in
    return try app.view("index.mustache")
}

app.start()
index.mustache
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>トップページ</title>
    </head>
    <body>
        <h1>Hello Vapor</h1>
    </body>
</html>

テンプレートの一部を動的に変更して表示するサンプル

main.swift
import Vapor
import VaporMustache

let mustache = VaporMustache.Provider()
let app = Application(providers: [mustache])

app.get("/") { request in
    return try app.view("index.mustache", context: [
        "message": "I love Swift:D"
    ])
}

app.start()
index.mustache
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>トップページ</title>
    </head>
    <body>
        <h1>{{ message }}</h1>
    </body>
</html>

main.swift側のkeyとindex.mustache側の{{ key }}が対応するようにする。

JSONを返すサンプル

main.swift
import Vapor

let app = Application()

app.get("/json") { request in
    return JSON([
        "name": "nnsnodnb",
        "job": [
            "category": "programmer",
            "language": "swift"
        ],
        "age": 20,
        "girl_friend": false
    ])
}

app.start()

POSTからデータを取得する

サンプルがあれなのでとりあえずJSONデータを返すもの

main.swift
import Vapor

let app = Application()

app.post("/json") { request in
    return JSON([
        // Optional型になっているので注意
        "age": request.data["age"].int!,
        "name": requeste.data["name"].string!
    ])
}

app.start()

CSSやJavaScript、画像をコンテンツとして配置する場合

Publicディレクトリを作成し、以下に適当にcssやらjsやらimgやらを追加することでルーティングすることなく簡単にロードさせることが可能。
割りと嬉しいです

ビルド & 実行

hoge.swiftを編集したあとは毎回コンパイルが必要です!

$ swift build
Compile Swift Module 'vapor_sample' (1 sources)
Linking .build/debug/vapor_sample
$ .build/debug/vapor_sample
Server starting at 0.0.0.0:8080

127.0.0.1:8080にアクセスできたら完了!

参考

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14