Hello, World!
First Application
Let us build our first application with WebGear. Create a new project with three files as shown below.
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Network.HTTP.Types as HTTP
import qualified Network.Wai.Handler.Warp as Warp
import WebGear.Server
main :: IO ()
main =
Warp.run 3000 $ toApplication $
method HTTP.GET $
path "/api/hello" $
proc request ->
respondA HTTP.ok200 PlainText -< "Hello, World!" :: Text
You can omit stack.yaml if you are not using stack.
Running the Server
Compile this program with Stack or Cabal and run it. Access the URL http://localhost:3000/api/hello and you should be
greeted with a message Hello, World!
.
Exploring the code
Here is an explanation of how the above code works:
- The
method HTTP.GET
function indicates that this API accepts only GET requests. - The
path "/api/hello"
function matches a specific request path, any request that does not match this path will result in a 404 response. - The
proc
notation is special syntax introduced by arrows. You should read the arrows chapter if you are not familiar with it. - Finally,
respondA
is used to send atext/plain
response with a body. - The
toApplication
converts its argument to a WAI application. This application is run as a Warp server usingWarp.run
.
We will see more details about all these in the upcoming chapters.