website is under construction
Standard Library

HTTP

import "ghost:http"

The http module runs a small HTTP server: register handlers for paths, then start listening.

Methods

http.handle()

Registers a handler for the given path pattern. The handler is a function taking one argument — a map describing the request.

Inside a handler, console.log() writes to the response body instead of the terminal. Whatever the handler prints is what the client receives.

http.handle("/", function(request) {
    console.log("hello world")
})

The request map holds:

KeyDescription
methodThe HTTP method, e.g. GET.
hostThe host the request was addressed to.
contentLengthThe length of the request body, in bytes.
protocolThe protocol version, e.g. HTTP/1.1.
protocolMajorThe major protocol version number.
protocolMinorThe minor protocol version number.
bodyThe request body as a string.
http.handle("/echo", function(request) {
    console.log(request.method + " " + request.body)
})

A pattern ending in / matches every path beneath it, and / on its own matches everything not matched by something more specific.

http.listen()

Starts the server on the given port, and runs the optional callback once it is up. This call blocks — nothing after it runs until the server stops.

http.listen(3000, function() {
    console.log("Server started at http://localhost:3000 🌱")
})

The server shuts down gracefully on Ctrl + C, giving in-flight requests up to 30 seconds to finish.

The module is deliberately minimal: there is no routing beyond the path patterns above, no way to set a status code or response headers, no route parameters, and no client for making outbound requests.