Tanguv0.35.0
/web/app/web/app/handlers/web/app/middleware/postgres/client/sqlite/client
Raw Markdown

Web apps & databases

Build full-stack HTTP/2 apps with routing, middleware, form validation, PostgreSQL primary/replica queries, and SQLite.

/http/serverHTTP/1.1 & HTTP/2Middleware ChainCSRF, CORS, ScriptsRouter & FormsTrie + ValidationHandler#shtml / JSON / SSE/postgres/clientPrimary + Replicas/sqlite/clientEmbedded PoolPrimary-strong reads: query-strong / query-one-strong · Read replicas: query / query-one
Full-stack request handling across /web/app, PostgreSQL primary/replica clusters, and SQLite.

Tangu ships a complete server stack in @standard: high-performance HTTP/1.1 & HTTP/2 serving (/http/server), composable routing and SSR/SPA helpers (/web/app/*), and native connection pools for both PostgreSQL (/postgres/client) and embedded SQLite (/sqlite/client).

Request lifecycle & routing #

Compose handlers from small functions using /web/app/handlers (chain-handlers, route-map, route-fs, route-graph, handle-html, handle-css).

(use {respond-html respond-json read-json} /web/app)
(use {chain-handlers handle-not-found route-map} /web/app/handlers)
(use {cors-middleware security-headers-middleware} /web/app/middleware)

(def handle-home (Func _req
    (respond-html #shtml [:html
        [:head [:title "My service"]]
        [:body [:h1 "Service online"]]
    ])
))

(def handle-health (Func _req
    (respond-json {:status "ok"})
))

(let app-routes (chain-handlers [
    (route-map {
        "/" handle-home
        "/healthz" handle-health
    })
    handle-not-found
]))

#pub
(let handler (|> app-routes
    (cors-middleware {:origins "*"} %0)
    (security-headers-middleware %0)
))

For multi-page websites, construct-app-graph-from-fs in /web/app/graph walks app/resources/ to power breadcrumb trails (get-trail), XML/text sitemaps (/web/app/graph/sitemap), and OpenAPI 3.1 schemas (/web/app/graph/openapi).

Middleware, forms & validation #

Use middlewares from /web/app/middleware to isolate cross-cutting concerns:

  • Script collection (scripts-middleware): Tracks (use-script "...") calls from nested UI components and injects deduplicated <script type="module"> imports or Stage SPA slot payloads.
  • Security & abuse protection: security-headers-middleware, csrf-middleware, cors-middleware, rate-limit-middleware, and basic-auth-middleware.
  • Sessions & observability: session-middleware (/web/app/session), request-id-middleware, tracing-middleware, and traceparent-middleware.
  • Typed form parsing (validate-form-middleware): Coerces URL-encoded or JSON bodies against a Struct schema, returning structured ValidationErrors (rendered via /web/app/forms <csrf-field> and <form-error>) on invalid input.
(use {read-form respond-error respond-json} /web/app)
(use {ValidationErrors} /validation)

(def Signup-Form (Struct
    #String #{:format :email} email
    #String #{:min-len 8} password
))

#pub
(def handle-signup (Func req
    (let parsed (read-form req Signup-Form))
    (when parsed
        ValidationErrors (respond-error 422 "validation-failed" {:errors parsed:errors})
        _ (respond-json {:created true :email parsed:email} 201)
    )
))

PostgreSQL (/postgres/client) #

/postgres/client executes asynchronously with /coro (await) and understands primary/replica database topologies. Choosing the right consistency helper prevents subtle stale-read bugs:

Function Routing Use when
query / query-one Replica when configured, else primary Read-heavy dashboards, listings, and eventually consistent lookups
query-strong / query-one-strong Primary writer strictly INSERT/UPDATE/DELETE ... RETURNING and post-mutation read-after-write flows
exec / exec-batch Primary writer strictly Single mutations or multi-statement DDL migrations
begin / commit / rollback Explicit primary transaction Atomic multi-step writes
(use {await} /coro)
(use {connect query query-one-strong exec} /postgres/client)

#pub
(def create-and-fetch-user (Func [pool #String email #String name]
    (let user (try (await (query-one-strong
        pool
        #sql "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING id, email, name"
        email
        name
    ))))
    user
))

SQLite (/sqlite/client) #

/sqlite/client provides a synchronous embedded SQLite connection pool (connect, query, query-one, exec, exec-batch) without needing (await ...). Transactions wrap a single-argument closure with (begin conn (Func tx ...))—returning cleanly commits the transaction, while returning an Error or panicking rolls it back.

(use {connect exec-batch exec query begin} /sqlite/client)

#pub
(def init-and-seed-db (Func db-path
    (let conn (try (connect db-path)))
    (try (exec-batch conn
        #sql "CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, label TEXT NOT NULL)"
    ))
    (try (begin conn (Func tx
        (exec tx #sql "INSERT INTO items (label) VALUES (?)" "alpha")
        (exec tx #sql "INSERT INTO items (label) VALUES (?)" "beta")
    )))
    (query conn #sql "SELECT id, label FROM items ORDER BY id")
))

See the full API pages for /web/app, /postgres/client, and /sqlite/client.