HAppS tutorial 0.9

From HaskellWiki
Jump to: navigation, search

Disclaimer: This is a draft.

Hello World

import HAppS
import HAppS.Server.StdConfig

main = start serverConfig{http=impl}

impl =[method GET $ ok "Hello World!"] -- GET / returns "HTTP/1.0 200 OK\nContent-Type: text/plain; charset=utf-8\n\nHello World!"

This simple app will respond with "Hello World!" in plain text when you access the root with a GET request.

  • start takes a configuration value of type (StdConfig a), where a is a suitable type to be used as the state of our application, and starts up the framework, so we only need to specify this configuration.
  • serverConfig is an "empty" configuration that we can use to build our one, it's of type StdConfig (), so the state is of type (), i.e. we won't use it.

But we substitute the http field with our impl, so the app actually does what we want.

  • impl is of type [ServerPart IO], where type ServerPart m = Reader Request (m (Maybe Result))

So it's a list of handlers, that are functions from Request to IO (Maybe Result) packed in the Reader monad. Request is an HTTP request and Result an HTTP response. For every request the framework tries each handler until it finds one that returns a Result and sends that back to the client.

  • Here we've only one handler: the expression |method GET $ ok "Hello World!"|.
    • method :: (Monad m, MatchMethod method) => method -> m Result -> ServerPart m

The function method takes the HTTP-method to match on and a (m Result), and constructs a (ServerPart m). This (ServerPart m) will return the result when the request is of the specified method and the URI path has been consumed: in this example only if the client requests /. Also m = IO here.

    • the IO Result is built by the expression ok "Hello World!":
      • ok :: (ToMessage mess) => mess -> IO Result

For every type in the ToMessage class, ok can take a value of that type and construct a Result in the IO monad. So since the instance of ToMessage for String is defined to construct a plain/text that simply contains the String, our response is indeed what we said earlier.