- Create a new project, routing-in-snap, with a simple stack template. We use lts-9.1 as a resolver package archive. You can use the latest one available on Stackage. Just make sure that you use the same resolver later to solve the dependency constraints:
stack --resolver lts-9.1 new routing-in-snap simple
- Add a dependency on the following libraries in the build-depends subsection of the executable section, as follows:
executable routing-in-snap hs-source-dirs: src main-is: Main.hs default-language: Haskell2010 build-depends: base >= 4.7 && < 5 , snap-server , snap-core , snap , lens , bytestring , text
- Use the following command to solve the dependency constraints to update the stack.yaml file:
stack --resolver lts-9.1 solver --update-config
- Open src/Main.hs. We will add our source here. Add the imports for Snap:
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Monoid import Control.Applicative import Snap import Snap.Core import Snap.Http.Server
- Add the routes. We will add two routes. The first route, hello, is where we will respond with a standard Hello World! greeting. The second route, greet/:nameparam, has a parameter embedded in the route. The parameter nameparam is embedded in the route path with a colon:
routes = [ ("hello", writeBS "Hello World!") , ("greet/:nameparam", greetHandler) ]
- Next, we will add a handler for the greet/:nameparam route. We access the named parameter with the getParam function. This may fetch us the value of the parameter. We write an error message if the parameter value is not specified:
greetHandler = do name <- getParam "nameparam" maybe (writeBS "nameparam not specified") (\n -> writeBS
("Welcome " <>n)) name
- Compose the routes in a single site. The top route and other routes are combined with <|> (an instance of the Alternative type class), as shown here:
site = ifTop (writeBS "Serving from root") <|> route routes
- Use the quickHttpServe method to serve the site:
main :: IO () main = quickHttpServe site
- Build and execute the project. Also create a folder, log, in the project directory. The access/error logs are stored in this folder:
stack build stack exec -- routing-in-snap
- The server will run at 0.0.0.0:8000; connect to the local host by pointing the browser to http://localhost:8000/greet/snap. You should see the following message:
