使用Scotty的Haskell REST服务:将JSON转换回数据

使用Scotty的Haskell REST服务:将JSON转换回数据,json,haskell,scotty,Json,Haskell,Scotty,我与Haskell和Scotty一起构建了一个REST服务,代码如下: {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} module Main where import Data.Monoid ((<>)) import Data.Aeson (FromJSON, ToJSON) import Data.Text.Lazy import GHC.Generics import Web.Scotty

我与Haskell和Scotty一起构建了一个REST服务,代码如下:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

module Main where

import Data.Monoid ((<>))
import Data.Aeson (FromJSON, ToJSON)
import Data.Text.Lazy
import GHC.Generics
import Web.Scotty

data Point = Point { x :: Int, y :: Int } deriving (Generic, Show)
instance ToJSON Point
instance FromJSON Point
movePoint :: Point -> Int -> Int -> Point
movePoint (Point x y) dx dy = Point (x + dx) (y + dy)

data Rectangle = Rectangle { width :: Int, height :: Int, point :: Point } deriving (Generic, Show)
instance ToJSON Rectangle
instance FromJSON Rectangle
move :: Rectangle -> Int -> Int -> Rectangle
move r@(Rectangle {point = p}) dx dy = r { point = movePoint p dx dy }

main = do
  putStrLn "Starting Server..."
  scotty 3000 $ do
    get "/rectangle/:id" $ do
      id <- param "id"      
      text id

    post "/rectangle" $ do
      rectangle <- jsonData :: ActionM Rectangle
      json rectangle    

    post "rectangle/move/:dx/:dy" $ do      
      dx <- param "dx"
      dy <- param "dy"
      rectangle <- jsonData :: ActionM Rectangle
      move rectangle dx dy
      json rectangle
{-#语言重载字符串}
{-#派生通用语言}
模块主要在哪里
导入数据。Monoid(())
import Data.Aeson(FromJSON,ToJSON)
导入Data.Text.Lazy
进口GHC.仿制药
导入Web.Scotty
数据点=点{x::Int,y::Int}派生(通用,显示)
实例到JSON点
来自JSON点的实例
移动点::点->整数->整数->点
移动点(点xy)dx dy=点(x+dx)(y+dy)
数据矩形=矩形{宽度::Int,高度::Int,点::点}派生(通用,显示)
实例ToJSON矩形
实例FromJSON矩形
移动::矩形->整数->整数->矩形
移动r@(矩形{point=p})dx dy=r{point=movePoint p dx dy}
main=do
putStrLn“正在启动服务器…”
斯科特3000美元
获取“/rectangle/:id”$do

id
move
只是一个生成
Rectange
的常规函数,但您可以在需要
action文本IO
的do块中使用它。我想你想要一个let语句:
let newRectanlge=move…
是的,这解决了这个问题,谢谢
move
只是一个常规函数,生成
Rectange
,但是你可以在需要
ActionT Text IO
的do块中使用它。我想你想要一个let station:
让newRectanlge=move…
是的,这解决了问题,谢谢
Couldn't match expected type `Web.Scotty.Internal.Types.ActionT
                                    Text IO a0'
                with actual type `Rectangle'
    In a stmt of a 'do' block: move rectangle dx dy
    In the second argument of `($)', namely
      `do { dx <- param "dx";
            dy <- param "dy";
            rectangle <- jsonData :: ActionM Rectangle;
            move rectangle dx dy;
            .... }'