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:
| Key | Description |
|---|---|
method | The HTTP method, e.g. GET. |
host | The host the request was addressed to. |
contentLength | The length of the request body, in bytes. |
protocol | The protocol version, e.g. HTTP/1.1. |
protocolMajor | The major protocol version number. |
protocolMinor | The minor protocol version number. |
body | The 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.