Wai   ルーティング

ホーム


ルーティング

Wai のルーティングを書いています。デプロイするかたちではなく、 ローカルで稼働させるかたちで書いています。

コーディング

任意のディレクトリに任意の Cabal ファイルを作ります。ここでは「wai」 ディレクトリに「app.cabal」を作りました。

app.cabal


name:                app
version:             0.1.0.0
category:            Web
build-type:          Simple
cabal-version:       >=1.10

executable app
  main-is:             Main.hs
  build-depends:       base >=4.7 && <5.0
                     , warp
                     , wai
                     , http-types
                     , bytestring
                     , text
  hs-source-dirs:      .
  default-language:    Haskell2010
    

wai ディレクトリに「Main.hs」ファイルを作ります。

Main.hs


{-# LANGUAGE OverloadedStrings #-}

import Network.Wai              (Application, responseLBS, pathInfo)
import Network.HTTP.Types       (ok200, notFound404)
import Network.Wai.Handler.Warp (run)
import Data.ByteString.Lazy     (fromStrict)
import Data.Text                (Text)
import Data.Text.Encoding       (encodeUtf8)
import Data.Monoid              ((<>))

app :: Application
app request respond =
    case pathInfo request of
        []              -> root request respond
        ["hello"]       -> hello request respond
        ["hello", name] -> helloName name request respond
        _               -> notFound request respond
        
root :: Application
root _ respond =
    respond $ responseLBS
        ok200
        [("Content-Type", "text/plain")]
        "Hello, Web!"
        
hello :: Application
hello _ respond =
    respond $ responseLBS
        ok200
        [("Content-Type", "text/plain")]
        "Hello!"

helloName :: Text -> Application
helloName name _ respond =
    respond $ responseLBS
        ok200
        [("Content-Type", "text/plain")]
        ("Hello, " <> (fromStrict $ encodeUtf8 name) <> "!")

notFound :: Application
notFound _ respond =
    respond $ responseLBS
        notFound404
        [("Content-Type", "text/plain")]
        "404 Not Found"

main :: IO ()
main = run 8080 app
    

ビルド

ターミナルで wai ディレクトリに移動して、次のようにビルドします。


$ stack init
すぐに終わります。
$ stack build
かなり時間がかかります。
    

実行

ターミナルに次のように入力して、サーバーを起動します。


$ stack exec app
    

ブラウザを起動して「localhost:8080/」にアクセスします。

確認

各アクセスに対する応答は次のようになります。


localhost:8080/
Hello, Web!

localhost:8080/hello
Hello!

localhost:8080/hello/app
Hello, app!

localhost:8080/app
404 Not Found
    

終了

サーバーを終了させるには、ターミナルで「Control」キーを押しながら「c」キーを 押します。


^C
    


5134 visits
Posted: Mar. 10, 2019
Update: Mar. 10, 2019

ホーム   ページトップ