【问题标题】:Scotty web service斯科蒂网络服务
【发布时间】:2017-09-28 17:09:03
【问题描述】:

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

Web 服务应响应获取请求,例如 /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 结果是:嗨,托尼,怎么了!

问题是我不知道如何更改代码以获得'/convert/15?to=usd&from=eur.'作为请求并得到正确的答案。

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

提前致谢。

最终解决方案编辑:

{-# 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

【问题讨论】:

  • 你有 /:convert/:amount 所以你在查询字符串之前有两个捕获。必须是/convert/:amount,转换前没有:
  • 这绝对是解决方案,非常感谢!

标签: haskell web service frameworks scotty


【解决方案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>"

我将把转换部分留给你弄清楚。使用 &lt;&gt; 代替 mconcat 似乎也更干净。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2011-09-15
    • 1970-01-01
    • 2018-02-05
    相关资源
    最近更新 更多