Http Server in PureScript

Here’s the translation of the HTTP server example from Go to PureScript:

Our HTTP server example demonstrates how to create a basic web server using PureScript. We’ll use the purescript-express library, which provides bindings to the Express.js web framework.

First, let’s set up our project and install the necessary dependencies:

$ spago init
$ spago install express

Now, let’s create our server code in a file named src/Main.purs:

module Main where

import Prelude

import Effect (Effect)
import Effect.Console (log)
import Node.Express.App (App, get, listenHttp)
import Node.Express.Response (send)
import Node.HTTP (Server)

-- A simple handler that responds with "hello"
hello :: App
hello = send "hello\n"

-- A handler that echoes back the request headers
headers :: App
headers = do
  req <- ask
  headersObj <- headers req
  send $ show headersObj

-- Our main function sets up the server and defines routes
main :: Effect Server
main = do
  app <- express

  -- Register our handlers with specific routes
  get "/hello" hello app
  get "/headers" headers app

  -- Start the server on port 8090
  server <- listenHttp app 8090 \_ ->
    log $ "Server listening on " <> show 8090

  pure server

In this PureScript version:

  1. We define two handler functions: hello and headers. These correspond to the Go handlers but are implemented using PureScript’s App type from the purescript-express library.

  2. The main function sets up the Express application, registers the routes, and starts the server.

  3. We use get to associate paths with handlers, similar to http.HandleFunc in Go.

  4. Instead of http.ListenAndServe, we use listenHttp to start the server.

To run the server:

$ spago run
Server listening on 8090

You can then access the server using curl:

$ curl localhost:8090/hello
hello

$ curl localhost:8090/headers
{ "user-agent": ["curl/7.64.1"], "accept": ["*/*"], "host": ["localhost:8090"] }

This PureScript implementation provides similar functionality to the Go example, showcasing how to create a basic HTTP server with multiple routes and custom handlers.