Home / Docs / Examples

health

Release v0.4.0

A health endpoint: an HTTP server that answers GET /health with 200 ok, and every other request with 404.

This is the example of ADR 0123, "A health endpoint" (HTTP servers), in the host-driven form of spec/31 §7: the package declares no main. Its ita.una names, in a serve section, the module whose handle the host calls once for each request it reads, and grants the address it listens on. The host owns every connection and answers each request with the reply handle returns, so the module itself is one ordinary function, which the checker, the verifier and the tests see as any other.

What it demonstrates:

Check and test it

From this directory:

sh
una check .   # copy examples/health
una test .
una report .

una test . runs the three tests, each with a request built by test_request:

una test .Output
test health "the health endpoint answers ok" ... ok
test health "every other path is not found" ... ok
test health "a request of another method is not found" ... ok

3 tests: 3 passed, 0 failed

una run . serves: it listens on 127.0.0.1:8080, answers each request with the reply of handle, and ends with exit code 0 when it is stopped (Ctrl-C or SIGTERM), after the requests in flight are answered (spec/31 §1 rule 10). una build . makes an executable, target/una/health, that serves the same way. The toolchain's own tests run it over loopback in both engines.

How it works

The serve section names the module health, and run grants holds the address:

ita.unauna
run
  grants
    serve "http://127.0.0.1:8080"

serve
  module health

handle answers from the method and the decoded path segments of the request. Its parameter and its result are internal: a reply carries what the server's peers may read, and a Reply built from secret data is refused.

Edition

Edition 0.4, a preview (edition).

Files

ita.unauna
ita health
  version 0.1.0
  edition 0.4

run
  grants
    serve "http://127.0.0.1:8080"

serve
  module health
ita.lock
-- Written by `una ita`; do not edit.
lock 1

solver
  encoding "una-smt-1"
  name "z3"
  version "5.1.0"
  logic "QF_UFLIA"
  steps 5000000
  seed 0
src/health.unauna
module health

import std.host (Method, Reply, Request)
import std.testing (test_request)

--- Answers `GET /health` with 200, and every other request with 404.
pub handle(request: internal Request) -> internal Reply
=
  if request.method is Get and request.segments == ["health"]
    Reply(status: 200, headers: [], body: "ok")
  else
    Reply(status: 404, headers: [], body: "")

test "the health endpoint answers ok"
  do handle(test_request(method: Get, target: "/health", body: ""))
  expect result.status == 200

test "every other path is not found"
  do handle(test_request(method: Get, target: "/other", body: ""))
  expect result.status == 404

test "a request of another method is not found"
  do handle(test_request(method: Post, target: "/health", body: ""))
  expect result.status == 404