purescript-httpurple/docs/Basics.md
Connor Prussin 8295d8755e
Clean up imports (#185)
* Clean up import declarations to only use qualified when necessary

* Remove unused imports
2021-11-18 22:16:35 -08:00

2.6 KiB

HTTPure Basics

This guide is a brief overview of the basics of creating a HTTPure server.

Creating a Server

To create a server, use HTTPure.serve (no SSL) or HTTPure.serveSecure (SSL). Both of these functions take a port number, a router function, and an Effect that will run once the server has booted. The signature of the router function is:

HTTPure.Request -> HTTPure.ResponseM

For more details on routing, see the Routing guide. For more details on responses, see the Responses guide. The router can be composed with middleware; for more details, see the Middleware guide.

Non-SSL

You can create an HTTPure server without SSL using HTTPure.serve:

main :: HTTPure.ServerM
main = HTTPure.serve 8080 router $ log "Server up"

Most of the examples, besides the SSL Example, use this method to create the server.

You can also create a server using a custom HTTP.ListenOptions value:

main :: HTTPure.ServerM
main = HTTPure.serve' customOptions router $ log "Server up"

SSL

You can create an SSL-enabled HTTPure server using HTTPure.serveSecure, which has the same signature as HTTPure.serve except that it additionally takes a path to a cert file and a path to a key file after the port number:

main :: HTTPure.ServerM
main =
  HTTPure.serveSecure 8080 "./Certificate.cer" "./Key.key" router $
    log "Server up"

You can look at the SSL Example, which uses this method to create the server.

You can also create a server using a HTTP.ListenOptions and a HTTPS.SSLOptions:

main :: HTTPure.ServerM
main =
  HTTPure.serveSecure' customSSLOptions customOptions router $
    log "Server up"

Shutdown hook

To gracefully shut down a server you can add a shutdown hook. For this you will need to add the following dependencies:

posix-types
node-process

Then take the closing handler returned by serve and create a SIGINT and SIGTERM hook:

import Prelude

import Data.Posix.Signal (Signal(SIGINT, SIGTERM))
import Effect (Effect)
import Effect.Console (log)
import HTTPure (serve, ok)
import Node.Process (onSignal)

main :: Effect Unit
main = do 
  closingHandler <- serve 8080 (const $ ok "hello world!") do
    log $ "Server now up on port 8080"

  onSignal SIGINT $ closingHandler $ log "Received SIGINT, stopping service now."
  onSignal SIGTERM $ closingHandler $ log "Received SIGTERM, stopping service now."