Skip to content

New Snap API Tutorial

Oskar Gewalli edited this page Dec 17, 2017 · 1 revision

NOTE: There have been some comments that the current snap tutorial has too much theory description getting in the way of concrete code examples. This tutorial is an attempt to rectify that. It is a work in progress. It may end up replacing the current tutorial or it may just become a different tutorial. That remains to be seen. I'm putting it here so other people can contribute and do a better job at keeping it up-to-date. It is written in markdown format. This format is different from the Textile format supported by Github, so it will look a little weird.

Examining Hello World

In the Quick Start Guide, we installed Snap and created a template "hello world" application. Here we'll look at what's inside the application and describe basic use of Snap's web server API.

snap init creates two files in the src directory, Common.hs and Main.hs. Common.hs contains general-purpose code that will eventually be integrated into the Snap framework so you won't have to carry this code with your application. For now, we've left it out to avoid unnecessary project dependencies. You don't need to worry about Common.hs unless you want an in-depth understanding of the infrastructure. Here's the important code in Main.hs:

site :: Snap ()
site =
    ifTop (writeBS "hello world") <|>
    dir "seeform" (method POST showParams) <|>
    route [ ("foo", writeBS "bar")
          , ("echo/:echoparam", echoHandler)
          ] <|>
    dir "static" (fileServe ".")

echoHandler :: Snap ()
echoHandler = do
    param <- getParam "echoparam"
    maybe (writeBS "must specify echo/param in URL")
          writeBS param

The behavior of this code can be summarized with the following rules:

  1. If the user requested the site's root page (http://mysite.com/), then return a page containing the string "hello world".
  2. If the user requested /foo, then return "bar".
  3. If the user requested /echo/xyz, then return "xyz".
  4. If the request URL begins with /static/, then look for files on disk matching the rest of the path and serve them.
  5. If none of these match, then Snap returns a 404 page.

Let's go over each of the Snap API functions used here.

ifTop only executes its argument if the client requested the root URL. Use this for your home page. It can also be combined with the dir function to define your index handler for a certain URL directory.

writeBS appends a strict ByteString to the response being constructed. Snap also provides an analogous function writeLBS for lazy ByteStrings. You can also use the functions writeText and writeLazyText if you use Data.Text instead of ByteString.

dir runs its action only if the request path starts with the specified directory. You can combine successive dir calls to match more than one subdirectory into the path.

Clone this wiki locally