Skip to content

Neel - 2.2.0

Latest

Choose a tag to compare

@Niminem Niminem released this 23 Nov 21:50

Neel 2.2.0

Neel 2.2 adds custom routes: answer HTTP requests with your own Nim procs, next to the web folder or instead of it. Nothing is removed or renamed; existing 2.1 apps compile and behave as before, apart from the small differences listed below. Verified on macOS, Windows, and Linux (Ubuntu) with Nim 2.2.12.

Custom routes

proc home(req: HttpRequest): HttpResponse =
  htmlResponse("<!doctype html><script src=\"/neel.js\"></script><h1>Hello</h1>")

proc user(req: HttpRequest): HttpResponse =
  textResponse("user " & req.param("id"))

proc slackHook(req: HttpRequest): HttpResponse =
  let event = parseJson(req.body)   # verify the sender's signature first
  try:
    js.showEvent(event)             # push it into the open page
  except NeelNoWindowError:
    discard                         # no page is open right now
  textResponse("ok")

startApp(routes = @[
  get("/", home),
  get("/users/@id", user),
  post("/hooks/slack", slackHook)])

Any method, with bodies. Build routes with get, post, put, patch, delete, or route({hmGet, hmPost}, ...). In a pattern, @name captures one path segment and a trailing *name captures the rest. Read them with req.param("name"), a query value with req.queryParam("x"), and the body with req.body. Answer with htmlResponse, textResponse, jsonResponse, redirectResponse, or initResponse(status, body, contentType) for anything else.

Same model as exposed procs. Handlers are plain top-level procs that run on the worker pool: they may block, and shared state needs a Lock. Inside one, js and currentWindow() refer to the window the request came from, or to the only open window when the request names none, so a webhook can push straight into the page. A handler that raises becomes a 500 and the app carries on.

Files first, routes for the rest. For GET and HEAD, a file in the web folder is served when one exists, and routes answer everything else in the order you list them. A catch-all like get("/*", ...) therefore never hides your CSS and JS. A path that matches a route only for other methods gets a 405 with the right Allow header. Mistakes in the route list, such as a route on /ws or /neel.js or one that an earlier route makes unreachable, raise ValueError at startup, before anything is bound.

No web folder needed. An app with routes runs without one: if there is no web folder next to your source file, the app is served from its routes alone, in debug and release builds. webDir = "" says so explicitly. A folder you name yourself must still exist, and an app with neither a folder nor routes fails at start, as before.

Both modes. Routes work the same in local mode and serve mode. In serve mode a route for / answers it in place of the redirect to startPath, and webhooks reach your handlers through your tunnel or proxy.

Safe by default against other websites. A POST, PUT, PATCH, or DELETE that a browser sends from another origin is refused with a 403. Other websites, pages served by other programs on your machine, and sibling subdomains behind your proxy cannot submit to your routes; your own pages can, with nothing to configure. Requests without browser headers, such as webhooks and curl, pass. Neel authenticates no one: verify a webhook's signature in its handler, and keep state changes out of GET routes.

Everything is in the guide's Custom routes section. examples/routes is a runnable app with no web folder: pages rendered in Nim, a form that posts to a route, and a webhook you can call with curl that pushes into the open page.

Limits

  • Request bodies are capped by the new maxBodySize parameter (default 1 MiB, the same limit as before); a larger body gets a 400.
  • Bodies must be sent with Content-Length; chunked uploads get a 400. multipart/form-data is not parsed: upload a file with fetch(url, {method: "POST", body: file}) and read req.body.
  • Responses are sent whole, with no streaming or server-sent events. Push to the page with js instead.
  • No CORS: pages on other origins cannot call your routes.

Changes for existing apps

  • A request with a method other than GET or HEAD that a browser sends from another origin now gets a 403. Before, every such request got a 405, so nothing that worked before is affected.
  • js.wait timeouts no longer end up to 1 ms early; js.wait(1).foo() used to not wait at all.

Minor updates

  • New exports: HttpRequest, HttpResponse, HttpMethod (hmGet, hmPost, ...), Route, RouteHandler, get, post, put, patch, delete, route, param, queryParam, initResponse, addHeader, setHeader, getHeader, hasHeader, htmlResponse, textResponse, jsonResponse, redirectResponse, and DefaultMaxBodySize. They are overloads by argument type, so someOption.get and mySeq.delete(i) keep working.
  • New startApp parameters: routes and maxBodySize.
  • Docs: a Custom routes section and What's new in 2.2 in the guide, a routes quick start in the README, and a webhook note in the Cloudflare walkthrough (not tested against Access, unlike the rest of that document).
  • Tests: the pending-call race test is now deterministic and no longer busy-spins. It failed now and then on macOS and could take minutes on some virtual machines.