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 expressNow, 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 serverIn this PureScript version:
We define two handler functions:
helloandheaders. These correspond to the Go handlers but are implemented using PureScript’sApptype from thepurescript-expresslibrary.The
mainfunction sets up the Express application, registers the routes, and starts the server.We use
getto associate paths with handlers, similar tohttp.HandleFuncin Go.Instead of
http.ListenAndServe, we uselistenHttpto start the server.
To run the server:
$ spago run
Server listening on 8090You 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.