お布団宇宙ねこ

にゃーん

Stack を使って Scotty 入門してみた

Haskell の Web フレームワークである Scotty を触ってみました。

Yesod で使えるなら Scotty でも同じようにできるだろうと思って今回も Stack を使ってみました。

Hello World 的なものを表示するまで

プロジェクトを新規作成してから setup までやっておきます。

stack new hello-scotty
cd hello-scotty
stack setup

次に、依存ライブラリとして Scotty を cabal ファイルに追記します。

executable hello-scotty-exe の段落に追記するのがポイントです。

( library ではありません)

hello-scotty.cabal

...

executable hello-scotty-exe
  hs-source-dirs:      app
  main-is:             Main.hs
  ghc-options:         -threaded -rtsopts -with-rtsopts=-N
  build-depends:       base
                     , scotty
                     , hello-scotty
  default-language:    Haskell2010

...

そして stack build

$ stack build

ansi-terminal-0.6.2.3: configure
ansi-terminal-0.6.2.3: build
base-compat-0.9.1: configure
base-compat-0.9.1: build
auto-update-0.1.4: configure
auto-update-0.1.4: build
appar-0.1.4: configure
appar-0.1.4: build

...
Completed 67 action(s).

終わったら次は Scotty の README に載っているサンプルをそのままコピペしましょう。

Haskell のコードを試すときは src ディレクトリ以下にファイルを置いてそれを stack ghci で読み込むようにしてますが、今回はちゃんとしたアプリケーションなので app/Main.hs に書いていきます。

app/Main.hs

{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty

import Data.Monoid (mconcat)

main = scotty 3000 $ do
    get "/:word" $ do
        beam <- param "word"
        html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"]

あとはサーバを起動するだけです。 stack exec で実行します。デフォルトだと [プロジェクト名]-exe が実行ファイル名になります。

$ stack exec hello-scotty-exe

Setting phasers to stun... (port 3000) (ctrl-c to quit)

見れました。

f:id:ku00:20170109113731p:plain

実はテンプレートがあった

Yesod のときは「テンプレート」というものを使って簡単にセットアップできたのですが、調べたら Scotty のものもあったという...。

(Yesod のは 公式のクイックスタート にも載っています )

github.com

使い方は簡単で、 stack new でプロジェクト名の後に使いたいテンプレート名を入れるだけです。

$ stack new template-hello-scotty scotty-hello-world

Downloading template "scotty-hello-world" to create project "template-hello-scotty" in template-hello-scotty/ ...
Looking for .cabal or package.yaml files to use to init the project.
Using cabal packages:
- template-hello-scotty/template-hello-scotty.cabal
...

生成されたファイルも最低限という印象。

f:id:ku00:20170109113735p:plain

まとめ

Stack を使うと一通りのことをやってくれるので本当に便利ですね。また、 Yesod と比べると Scotty は依存ライブラリがそこまで多くないのでセットアップに時間がかからないです。

さて、次からは本格的なの作っていくぞ。

参考文献