Scotty网络服务

时间:2017-05-01 08:44:41

标签: haskell web service frameworks scotty

我需要创建一个Web服务,使用Haskell中的 scotty web framework 在不同的货币之间进行转换。

网络服务应该响应获取请求,例如/ convert / 15?to = usd& from = eur。

到目前为止我有这个代码:

{-# LANGUAGE OverloadedStrings #-}

import Web.Scotty
import Data.Monoid (mconcat)

functionxs :: a -> Int
functionxs a = 5

main = scotty 3000 $ do
  get "/:word" $ do
    name <- param "word"
    html $ mconcat ["<h1>Hi, ", name, " what's up!</h1>"]

因此,当您在浏览器中执行时:http://localhost:3000/Tony 结果是:嗨,托尼,什么了!

问题在于我不知道如何更改代码以便将&#39; / convert / 15?to = usd&amp; from = eur。&#39;作为要求并得到正确的答案。

希望任何人都可以帮助我。

提前致谢。

使用最终解决方案编辑:

{-# LANGUAGE OverloadedStrings #-}

import Web.Scotty
import Data.Monoid (mconcat)
import Data.Text.Lazy (Text, pack)

main = scotty 3000 $ do
    get "/convert/:amount" $ do
        money <- param "amount"
        to <- param "to"
        frm <- param "from"
        html $ mconcat ["<h1>The result is: ", pack (show (convert 
money to frm)),  "</h1>"]

convert :: Double -> String -> String -> Double
convert a b c = if (b=="euro" && c=="usd") 
            then (a*1.091)
            else if (b=="usd" && c=="euro")
            then (a*0.915)
            else 0

1 个答案:

答案 0 :(得分:1)

查看docs,您需要调用param来获取所需内容。

尝试此作为起点:

{-# LANGUAGE OverloadedStrings #-}

import Web.Scotty
import Data.Monoid

main = scotty 3000 $ do
  get "/convert/:amt" $ do
  amt <- param "amt"
  frm <- param "from"
  to <- param "to"
  html $ "<h1>" <> amt <>" in " <> frm <> " is " <> to <> "</h1>"

我会留下转换件让你弄明白。使用<>代替mconcat似乎也更清晰。