greenServeFEgreenServeFE documentation

Documentation home / Web development

Complete practical reference · Native C server module

Build complete web applications with greenServeFE

This guide takes the server module beyond a hello-world listener. It documents the API exported by the native server.c implementation and provides substantial GSVE examples for HTML websites, reusable templates, product catalogs, shopping carts, sales records, inventory workflows, admin dashboards, JSON endpoints, middleware, file delivery and HTTPS.

What this guide covers
HTTP routingMiddlewareRequest parsingResponse API
HTML pagesTemplatesConstructStatic files
ShopSalesInventoryAdmin
JSON APIHTTP clientTLSSecurity
Source alignment: API names and behavior below are derived from the greenServeFE native server.c implementation and the build repository's documented construct integration. Examples use the actual GSVE declaration keyword define and function syntax. The optional native module must be built and installed separately; a core VM build does not automatically include this networking runtime.

Contents

  1. Architecture and setup
  2. First server
  3. Routes and parameters
  4. Request object
  5. Complete response API
  6. Middleware
  7. HTML templates
  8. Construct HTML generation
  9. Complete storefront
  10. Inventory management
  11. Sales and order workflows
  12. Admin dashboard
  13. JSON API patterns
  14. Static files and downloads
  15. Outbound HTTP client
  16. HTTPS and deployment
  17. Security and operational limits
  18. Full export inventory

Architecture and setup

The server is an optional native module, not a language keyword. The program imports it with import server;. The C module exposes route registration, a socket listener, response helpers, template/file functions and libcurl-based outbound HTTP functions.

Request lifecycle

Client TCP listener request parser route match matching middleware route handler response serialization client

The current listener accepts a connection and forks a child process to handle it. That matters for application design: ordinary in-memory mutations made while handling a request are not a durable shared database. Use a database or another persistent store for carts, stock, orders and user records.

Build and install

  1. Open the greenServeFE build repository and run its manual workflow for building the construct and server native modules.
  2. Install the resulting server.so (and construct.so if you use it) in a directory searched by the native module loader.
  3. Configure GREENSERVE_MODULE_PATH and, where required by the shared libraries, LD_LIBRARY_PATH.
  4. Run the GSVE program with the greenServeFE executable.
export GREENSERVE_MODULE_PATH=/usr/local/lib/modules
export LD_LIBRARY_PATH=/usr/local/lib/modules:$LD_LIBRARY_PATH
greenServeFE app.gsve

The exact package contents and linked system libraries depend on the module build workflow and release. Confirm that the installed shared object is compatible with the VM native-module ABI.

First server: a complete small site

Create app.gsve. The server root is the current directory; this minimal example disables automatic static serving and explicitly registers its routes.

import server;

func home(req, res) {
    res.status(200);
    res.set("X-Powered-By", "greenServeFE");
    res.html("<!doctype html><html lang='en'><head><meta charset='utf-8'><title>My site</title></head><body><h1>Hello from GSVE</h1><p>A native HTTP route.</p></body></html>");
}

func health(req, res) {
    res.json({ok: true, service: "storefront"});
}

server.get("/", home);
server.get("/health", health);
server.serve(".", 8080, {host: "0.0.0.0", static: false});

Open http://127.0.0.1:8080/ on the machine running the server. If you bind to 0.0.0.0, the listener accepts connections on available IPv4 interfaces; use firewall rules to control who can reach it.

Routes, methods, parameters and matching

Register handlers before calling serve. A route handler receives exactly two arguments: func handler(req, res). Named path segments use a colon; a wildcard segment is supported by the route matcher. Exact routes are preferred over less-specific matches. Middleware registered with use is prefix-matched.

RegistrationHTTP methodUse
server.get(path, handler)GETRead pages and resources
server.post(path, handler)POSTCreate or submit data
server.put(path, handler)PUTReplace a resource
server.patch(path, handler)PATCHPartially update a resource
server.delete(path, handler)DELETEDelete a resource
server.options(path, handler)OPTIONSHandle OPTIONS requests
server.any(path, handler)AnyMatch any method
server.page(path, html)GETRegister a fixed HTML string
server.use(prefix, handler)MiddlewareRun middleware for a path prefix
server.clear_routes()—Clear all registered routes

Named route parameters and query strings

import server;

func product_detail(req, res) {
    define product_id = req.params.id;
    define page_number = req.query.page;
    res.json({
        id: product_id,
        page: page_number,
        route: req.path
    });
}

func search(req, res) {
    res.json({
        term: req.query.q,
        sort: req.query.sort,
        raw_query: req.queryString
    });
}

server.get("/products/:id", product_detail);
server.get("/search", search);
server.serve(".", 8080, {static: false});

For /products/sku-42?page=2, the path parameter is available as req.params.id; query parameters are available as properties of req.query. Query decoding handles percent-encoded values and plus signs.

Wildcard route

func catch_all(req, res) {
    res.json({requested: req.params.wildcard});
}
server.get("/docs/*", catch_all);

Request object: fields and parsing

FieldType / meaning
req.methodHTTP method text, such as GET or POST
req.pathURL path without the query string
req.queryStringRaw query-string text
req.queryObject containing decoded query parameters
req.bodyRequest body as text
req.formURL-encoded form fields parsed into an object
req.headersRequest header object
req.paramsNamed route parameters, when present
req.cookiesCookie name/value object parsed from the Cookie header
req.isJsonBoolean indicating an application/json content type
req.contentTypeContent-Type header, when present
req.isAjaxBoolean based on X-Requested-With: XMLHttpRequest

Read a form submission

import server;

func contact_submit(req, res) {
    define name = req.form.name;
    define email = req.form.email;
    define message = req.form.message;

    if (name == null || email == null || message == null) {
        res.status(400);
        res.json({ok: false, error: "Missing required form fields"});
        return;
    }

    res.json({ok: true, received: {name: name, email: email}});
}

server.post("/contact", contact_submit);
server.serve(".", 8080, {static: false});

Read a JSON request body

The native request parser exposes the body as text and marks JSON content types with req.isJson. This server module does not itself provide a JSON parser for turning arbitrary request-body text into a nested GSVE object. For production JSON APIs, use a JSON parsing module available in your build, or accept explicitly defined form fields. Do not assume req.body is already an object.

Complete response API

MethodSignatureBehavior
res.statusstatus(code)Set numeric HTTP status code.
res.setset(name, value)Set a response header; CR/LF is rejected.
res.headerheader(name, value)Alias for set.
res.cookiecookie(name, value, maxAge?, secure?)Set a cookie with Path=/ and SameSite=Lax; optional max-age and secure/httpOnly flags.
res.clearCookieclearCookie(name)Set an empty cookie with Max-Age=0.
res.typetype(contentType)Set the response content type.
res.sendsend(value)Send text as text; non-string values are serialized as JSON.
res.texttext(value)Send text/plain.
res.noContentnoContent()Send status 204 with an empty body.
res.jsonjson(value)Serialize GSVE values as JSON and send application/json.
res.jsonpjsonp(value, callback)Send JSONP; callback must be a dotted JavaScript identifier.
res.htmlhtml(markup)Send HTML as text/html. Markup is inserted as supplied.
res.redirectredirect(url)Set Location and default to status 302; rejects CR/LF and unsupported schemes.
res.sendFilesendFile(relativePath)Send a file under the configured server root after path-safety checks.
res.downloaddownload(path, filename?)Send a file as an attachment with a validated filename.
res.renderrender(relativePath, data?)Read a template under the server root and substitute placeholders.

Response examples

func created(req, res) {
    res.status(201);
    res.set("Location", "/api/items/42");
    res.json({ok: true, id: 42});
}

func not_found(req, res) {
    res.status(404);
    res.type("text/plain; charset=utf-8");
    res.send("Resource not found");
}

func redirect_to_shop(req, res) {
    res.redirect("/shop");
}

func export_file(req, res) {
    res.download("exports/catalog.csv", "catalog.csv");
}

Response helpers end the response when they send a body. Set the status and headers before sending. res.send is polymorphic: strings are emitted as text; other supported VM values are serialized as JSON.

Middleware and request guards

Middleware is registered with server.use(prefix, handler). Its signature is func middleware(req, res, next). Call next() to continue. Sending a response or returning without calling next() stops the chain. Middleware executes in registration order for matching prefixes.

import server;

func request_headers(req, res, next) {
    res.set("X-Content-Type-Options", "nosniff");
    res.set("X-Frame-Options", "DENY");
    res.set("Referrer-Policy", "strict-origin-when-cross-origin");
    next();
}

func admin_gate(req, res, next) {
    define token = req.headers["X-Admin-Token"];
    if (token == "replace-this-demo-token") {
        next();
    } else {
        res.status(401);
        res.json({ok: false, error: "Authentication required"});
    }
}

server.use("/", request_headers);
server.use("/admin", admin_gate);

func admin_home(req, res) {
    res.html("<h1>Admin area</h1>");
}
server.get("/admin", admin_home);
server.serve(".", 8080, {static: false});
Authentication example warning: the hard-coded token above is only a teaching illustration. Do not deploy a shared token embedded in source. Use a persistent user/session system, strong secrets from environment configuration, secure cookies, and authorization checks on every protected operation. The server's cookie helper is not a complete session framework.

HTML templates with server.render

The server template engine replaces {{name}} placeholders using values from an object. Dotted paths such as {{customer.name}} are supported. A missing or null value produces an empty substitution. It does not implement loops, conditions, includes, layouts or automatic HTML escaping.

Template file: views/product.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>{{product.name}} | Northstar Shop</title>
  <link rel="stylesheet" href="/assets/site.css">
</head>
<body>
  <header><a href="/">Northstar Shop</a></header>
  <main>
    <p>SKU: {{product.sku}}</p>
    <h1>{{product.name}}</h1>
    <p>{{product.description}}</p>
    <strong>{{product.price_label}}</strong>
    <form method="post" action="/cart/add">
      <input type="hidden" name="sku" value="{{product.sku}}">
      <label>Quantity <input type="number" name="quantity" value="1" min="1"></label>
      <button type="submit">Add to cart</button>
    </form>
  </main>
</body>
</html>

Route that renders the template

import server;

func product_page(req, res) {
    define product = {
        name: "Field Notebook",
        sku: "NOTE-01",
        description: "A durable everyday notebook.",
        price_label: "$12.00"
    };
    res.render("views/product.html", {product: product});
}

server.get("/products/notebook", product_page);
server.serve(".", 8080, {static: false});
Critical template safety: the current C template renderer inserts values directly into the output. It does not HTML-escape them. Never interpolate user-submitted names, descriptions, search strings, comments or database content into HTML without escaping for the correct output context. Prefer construct.escape(value) when using the construct module, or a reviewed context-aware escaping routine. Attribute values and JavaScript contexts need their own escaping rules. Do not treat a template placeholder as safe by default.

Inline templates with server.render

The module-level server.render(template, data) function renders a template string in memory; res.render(file, data) reads a template file beneath the server root and sends the rendered HTML response.

import server;

func welcome(req, res) {
    define template = "<main><h1>Hello, {{profile.name}}</h1><p>Plan: {{profile.plan}}</p></main>";
    define page = server.render(template, {
        profile: {name: "Ada", plan: "Starter"}
    });
    res.html(page);
}

server.get("/welcome", welcome);
server.serve(".", 8080, {static: false});

Generate semantic HTML with construct

The optional construct module complements the server. Use it to create complete documents, semantic elements, metadata, links, styles and scripts from GSVE. Its element/text helpers escape text and validate supported attributes; the page body, CSS and JavaScript slots are trusted raw insertion points.

import construct;
import server;

define navigation =
    "<nav>" +
    construct.link("Home", "/") +
    construct.link("Products", "/products") +
    construct.link("About", "/about") +
    "</nav>";

define main_content =
    construct.element("h1", "A shop generated by GSVE") +
    construct.element("p", "HTML is composed in the server program.") +
    construct.element("a", "Browse the catalog", {href: "/products"});

define document = construct.page({
    lang: "en",
    title: "Northstar Shop",
    body: navigation + "<main>" + main_content + "</main>",
    css: "body{font:16px system-ui;margin:0;color:#172033}nav{padding:1rem;background:#10243a}nav a{color:white;margin-right:1rem}main{max-width:900px;margin:3rem auto;padding:1rem}",
    js: "console.log('Northstar Shop ready');"
});

func home(req, res) {
    res.html(document);
}

server.get("/", home);
server.serve(".", 8080, {static: false});

Construct API quick reference

FunctionPurpose
construct.page(options)Build a full HTML document; options include title, body, css, js and lang.
construct.document(options)Document-building alias / companion API.
construct.element(tag, text, attrs?)Build an HTML element with escaped text and validated supported attributes.
construct.meta(name, content)Create an allowlisted metadata element.
construct.link(label, href)Create a navigation link with escaped label and URL validation.
construct.escape(value)Escape a value for HTML text insertion.
construct.style(css)Wrap trusted CSS source.
construct.script(js)Wrap trusted JavaScript source.
construct.render(template, data)Render a template with escaped substitutions.

Complete example: product storefront

This example shows a multi-route shop with a home page, product listing, product details, a search route, an HTML checkout form, a cart submission endpoint and order confirmation. It is a runnable teaching skeleton with a small in-memory catalog. The catalog is read-only; the cart/order confirmation is illustrative and is not persistent. For real transactions, store cart and order records in gs_db or another durable database.

import construct;
import server;

define products = [
    {sku: "BAG-100", name: "Canvas Field Bag", category: "Bags", price: 38, stock: 12, description: "A practical everyday carry bag."},
    {sku: "NOTE-210", name: "Hardcover Notebook", category: "Stationery", price: 14, stock: 40, description: "A sturdy notebook for plans and ideas."},
    {sku: "LAMP-310", name: "Desk Lamp", category: "Home", price: 52, stock: 7, description: "Adjustable light for a focused workspace."},
    {sku: "MUG-410", name: "Ceramic Mug", category: "Home", price: 18, stock: 25, description: "A simple ceramic coffee mug."}
];

func money(value) {
    return "$" + str(value);
}

func layout(title, content) {
    define nav = "<header><a href='/'>Northstar Market</a><nav>" +
        construct.link("Shop", "/products") +
        construct.link("About", "/about") +
        construct.link("Cart", "/cart") +
        "</nav></header>";
    return construct.page({
        title: title + " | Northstar Market",
        lang: "en",
        body: nav + "<main class='container'>" + content + "</main>",
        css: "body{margin:0;font:16px system-ui;color:#182536;background:#f4f7fb}header{display:flex;justify-content:space-between;padding:1rem 5%;background:#14283e;color:white}header a{color:white;margin-right:1rem}main{max-width:1050px;margin:2rem auto;padding:1rem}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:1rem}.card{background:white;border:1px solid #dce4ed;border-radius:12px;padding:1rem}.price{font-size:1.3rem;font-weight:bold;color:#087f5b}button{padding:.7rem 1rem;background:#087f5b;color:white;border:0;border-radius:7px}input{padding:.6rem;border:1px solid #ccd5df;border-radius:6px}",
        js: ""
    });
}

func find_product(sku) {
    for product in products {
        if (product.sku == sku) {
            return product;
        }
    }
    return null;
}

func home(req, res) {
    define body = "<section><h1>Useful things, thoughtfully selected.</h1>" +
        "<p>Browse the catalog and discover the current collection.</p>" +
        "<a href='/products'>Explore products </a></section>";
    res.html(layout("Welcome", body));
}

func product_list(req, res) {
    define cards = "";
    for product in products {
        define safe_name = construct.escape(product.name);
        define safe_sku = construct.escape(product.sku);
        define safe_category = construct.escape(product.category);
        cards = cards + "<article class='card'><p>" + safe_category + "</p>" +
            "<h2>" + safe_name + "</h2>" +
            "<p class='price'>" + money(product.price) + "</p>" +
            "<p>Available: " + str(product.stock) + "</p>" +
            "<a href='/products/" + safe_sku + "'>View details</a></article>";
    }
    res.html(layout("Products", "<h1>Product catalog</h1><div class='cards'>" + cards + "</div>"));
}

func product_detail(req, res) {
    define product = find_product(req.params.sku);
    if (product == null) {
        res.status(404);
        res.html(layout("Not found", "<h1>Product not found</h1><a href='/products'>Back to shop</a>"));
        return;
    }
    define safe_name = construct.escape(product.name);
    define safe_description = construct.escape(product.description);
    define safe_sku = construct.escape(product.sku);
    define body = "<article><p>" + construct.escape(product.category) + "</p>" +
        "<h1>" + safe_name + "</h1><p>" + safe_description + "</p>" +
        "<p class='price'>" + money(product.price) + "</p>" +
        "<p>In stock: " + str(product.stock) + "</p>" +
        "<form method='post' action='/cart/add'>" +
        "<input type='hidden' name='sku' value='" + safe_sku + "'>" +
        "<label>Quantity <input type='number' name='quantity' value='1' min='1' max='10'></label> " +
        "<button type='submit'>Add to cart</button></form></article>";
    res.html(layout(product.name, body));
}

func search_products(req, res) {
    define term = req.query.q;
    if (term == null) {
        term = "";
    }
    define matches = "";
    for product in products {
        if (contains(str(product.name), str(term))) {
            matches = matches + "<li>" + construct.link(product.name, "/products/" + product.sku) + "</li>";
        }
    }
    res.html(layout("Search", "<h1>Search results</h1><ul>" + matches + "</ul>"));
}

func cart_add(req, res) {
    define sku = req.form.sku;
    define quantity = num(req.form.quantity);
    define product = find_product(sku);
    if (product == null || quantity < 1 || quantity > 10 || quantity > product.stock) {
        res.status(400);
        res.html(layout("Cart", "<h1>Unable to add item</h1><p>Check the SKU, quantity and stock.</p>"));
        return;
    }
    res.cookie("last_sku", product.sku, 86400, false);
    res.html(layout("Cart", "<h1>Added to cart</h1><p>" +
        construct.escape(product.name) + " × " + str(quantity) + "</p>" +
        "<p>This demo confirms the form flow but does not persist cart contents.</p>" +
        "<a href='/products'>Continue shopping</a>"));
}

func checkout_form(req, res) {
    define body = "<h1>Checkout</h1><form method='post' action='/checkout'>" +
        "<label>Full name <input name='customer' required></label><br>" +
        "<label>Email <input type='email' name='email' required></label><br>" +
        "<label>Delivery address <textarea name='address' required></textarea></label><br>" +
        "<button type='submit'>Place demo order</button></form>";
    res.html(layout("Checkout", body));
}

func checkout_submit(req, res) {
    if (req.form.customer == null || req.form.email == null || req.form.address == null) {
        res.status(400);
        res.html(layout("Checkout error", "<h1>Please complete all fields.</h1>"));
        return;
    }
    res.status(201);
    res.html(layout("Order received", "<h1>Thank you, " +
        construct.escape(req.form.customer) + "</h1><p>Your demo order was received.</p>"));
}

func about(req, res) {
    res.html(layout("About", "<h1>About Northstar Market</h1><p>A sample storefront built with GSVE routes and native HTML helpers.</p>"));
}

server.get("/", home);
server.get("/products", product_list);
server.get("/products/:sku", product_detail);
server.get("/search", search_products);
server.post("/cart/add", cart_add);
server.get("/checkout", checkout_form);
server.post("/checkout", checkout_submit);
server.get("/about", about);

server.serve(".", 8080, {host: "0.0.0.0", static: false, index: "index.html"});
Important example limitation: the storefront catalog is static demonstration data. The current server forks a child for each accepted connection, so changing a GSVE array during one request does not create a reliable cross-request cart or inventory store. Persist every order, cart and stock change in SQLite or another database. Also add CSRF protection, authentication, payment-provider verification, idempotency and transaction handling before accepting real orders or money.

Inventory management: products, stock and restocking

Inventory requires durable storage. The following illustrates the route design and validation boundary; connect the persistence calls to the installed gs_db module and use parameterized SQL. Do not replace database persistence with mutable global arrays in a fork-per-request server.

Inventory page and adjustment form

import construct;
import server;

func inventory_page(req, res) {
    define rows =
        "<tr><td>BAG-100</td><td>Canvas Field Bag</td><td>12</td><td>38.00</td></tr>" +
        "<tr><td>NOTE-210</td><td>Hardcover Notebook</td><td>40</td><td>14.00</td></tr>" +
        "<tr><td>LAMP-310</td><td>Desk Lamp</td><td>7</td><td>52.00</td></tr>";
    define body = "<h1>Inventory</h1><p>Review current stock levels and record a restock.</p>" +
        "<table><thead><tr><th>SKU</th><th>Product</th><th>On hand</th><th>Unit price</th></tr></thead><tbody>" +
        rows + "</tbody></table>" +
        "<h2>Record stock adjustment</h2><form method='post' action='/admin/inventory/adjust'>" +
        "<label>SKU <input name='sku' required></label>" +
        "<label>Quantity change <input name='delta' type='number' required></label>" +
        "<label>Reason <select name='reason'><option>restock</option><option>correction</option><option>damaged</option></select></label>" +
        "<button type='submit'>Save adjustment</button></form>";
    res.html(construct.page({title: "Inventory", body: body}));
}

func inventory_adjust(req, res) {
    define sku = req.form.sku;
    define delta = num(req.form.delta);
    if (sku == null || req.form.delta == null || delta == 0) {
        res.status(400);
        res.json({ok: false, error: "A SKU and non-zero quantity change are required"});
        return;
    }
    # Replace this point with a parameterized database transaction:
    # 1. Read the current quantity for this SKU.
    # 2. Reject unknown SKUs and any result below zero.
    # 3. Update products.stock and insert an inventory_movements row.
    # 4. Commit both writes together.
    res.status(202);
    res.json({ok: true, sku: sku, quantity_change: delta, reason: req.form.reason, persisted: false});
}

server.get("/admin/inventory", inventory_page);
server.post("/admin/inventory/adjust", inventory_adjust);
server.serve(".", 8080, {static: false});

Suggested relational schema

CREATE TABLE products (
    id INTEGER PRIMARY KEY,
    sku TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL,
    description TEXT NOT NULL DEFAULT '',
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0),
    active INTEGER NOT NULL DEFAULT 1
);

CREATE TABLE inventory_movements (
    id INTEGER PRIMARY KEY,
    product_id INTEGER NOT NULL,
    quantity_delta INTEGER NOT NULL,
    reason TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (product_id) REFERENCES products(id)
);

Use integer minor currency units (for example cents) instead of floating-point values for money. Keep an append-only movement record so stock changes can be audited. Apply stock changes atomically and prevent a sale from making stock negative.

Sales, orders and checkout

A sales system needs an order header, order lines, customer details, payment state and inventory movement records. The route handlers below show the HTTP contract and validation pattern; the persistence and payment provider integration must be implemented in the application layer.

Sales report page

import construct;
import server;

func sales_report(req, res) {
    define rows =
        "<tr><td>2026-11-01</td><td>ORD-1001</td><td>Ada Customer</td><td>2</td><td>$76.00</td><td>Paid</td></tr>" +
        "<tr><td>2026-11-02</td><td>ORD-1002</td><td>Lin Customer</td><td>1</td><td>$52.00</td><td>Pending</td></tr>" +
        "<tr><td>2026-11-03</td><td>ORD-1003</td><td>Mira Customer</td><td>3</td><td>$42.00</td><td>Paid</td></tr>";
    define body = "<h1>Sales report</h1>" +
        "<section class='metrics'><article><strong>$170.00</strong><p>Gross sales (sample)</p></article>" +
        "<article><strong>6</strong><p>Items sold (sample)</p></article>" +
        "<article><strong>3</strong><p>Orders (sample)</p></article></section>" +
        "<h2>Recent orders</h2><table><thead><tr><th>Date</th><th>Order</th><th>Customer</th><th>Items</th><th>Total</th><th>Status</th></tr></thead><tbody>" +
        rows + "</tbody></table>";
    res.html(construct.page({
        title: "Sales report",
        body: body,
        css: ".metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:1rem}.metrics article{background:#edf3f8;padding:1rem;border-radius:10px}.metrics strong{font-size:1.7rem}"
    }));
}

func order_detail(req, res) {
    define order_id = req.params.id;
    # Load the order and its lines from persistent storage here.
    res.json({ok: true, order_id: order_id, note: "Connect this handler to the orders database"});
}

func order_status_update(req, res) {
    define order_id = req.params.id;
    define status = req.form.status;
    if (status != "pending" && status != "paid" && status != "fulfilled" && status != "cancelled") {
        res.status(400);
        res.json({ok: false, error: "Unsupported order status"});
        return;
    }
    # Verify authorization and apply a valid state transition in a DB transaction.
    res.json({ok: true, order_id: order_id, requested_status: status, persisted: false});
}

server.get("/admin/sales", sales_report);
server.get("/admin/orders/:id", order_detail);
server.post("/admin/orders/:id/status", order_status_update);
server.serve(".", 8080, {static: false});

Suggested order schema

CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    order_number TEXT NOT NULL UNIQUE,
    customer_name TEXT NOT NULL,
    customer_email TEXT NOT NULL,
    total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
    status TEXT NOT NULL DEFAULT 'pending',
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE order_items (
    id INTEGER PRIMARY KEY,
    order_id INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    sku TEXT NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0),
    FOREIGN KEY (order_id) REFERENCES orders(id),
    FOREIGN KEY (product_id) REFERENCES products(id)
);

Admin dashboard and navigation

import construct;
import server;

func admin_layout(title, content) {
    define menu = "<aside><h2>Northstar Admin</h2>" +
        construct.link("Overview", "/admin") +
        construct.link("Products", "/admin/products") +
        construct.link("Inventory", "/admin/inventory") +
        construct.link("Sales", "/admin/sales") +
        construct.link("Orders", "/admin/orders") +
        "</aside>";
    return construct.page({
        title: title + " | Admin",
        body: menu + "<main>" + content + "</main>",
        css: "body{margin:0;display:grid;grid-template-columns:220px 1fr;font:16px system-ui;background:#f3f6fa;color:#172033}aside{min-height:100vh;background:#14283e;padding:1.2rem;display:flex;flex-direction:column;gap:1rem}aside h2,aside a{color:white}main{padding:2rem}.stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:1rem}.stat{background:white;border:1px solid #dce4ed;border-radius:10px;padding:1rem}.stat strong{font-size:1.7rem}"
    });
}

func admin_home(req, res) {
    define body = "<h1>Dashboard</h1><p>Store performance at a glance.</p>" +
        "<section class='stat-grid'>" +
        "<article class='stat'><strong>128</strong><p>Orders this month</p></article>" +
        "<article class='stat'><strong>$8,420</strong><p>Sample revenue</p></article>" +
        "<article class='stat'><strong>24</strong><p>Low-stock products</p></article>" +
        "</section><p>These are illustrative figures. Replace them with database aggregates.</p>";
    res.html(admin_layout("Overview", body));
}

func admin_products(req, res) {
    res.html(admin_layout("Products", "<h1>Product management</h1><p>Add, edit, archive and inspect products using persistent database-backed routes.</p><a href='/admin/inventory'>Manage stock</a>"));
}

func admin_orders(req, res) {
    res.html(admin_layout("Orders", "<h1>Orders</h1><p>Review order status, customer details and line items.</p><a href='/admin/sales'>View sales report</a>"));
}

server.get("/admin", admin_home);
server.get("/admin/products", admin_products);
server.get("/admin/inventory", inventory_page);
server.get("/admin/sales", sales_report);
server.get("/admin/orders", admin_orders);
server.serve(".", 8080, {static: false});

The dashboard page above composes HTML using literal trusted markup and the construct module. The route data shown is sample content, not live analytics.

JSON APIs and CRUD route structure

import server;

func list_products(req, res) {
    res.json({
        ok: true,
        items: [
            {sku: "BAG-100", name: "Canvas Field Bag", price_cents: 3800},
            {sku: "NOTE-210", name: "Hardcover Notebook", price_cents: 1400}
        ],
        count: 2
    });
}

func get_product(req, res) {
    define sku = req.params.sku;
    res.json({ok: true, sku: sku});
}

func create_product(req, res) {
    define sku = req.form.sku;
    define name = req.form.name;
    define price = num(req.form.price_cents);
    if (sku == null || name == null || req.form.price_cents == null || price < 0) {
        res.status(400);
        res.json({ok: false, error: "Invalid product fields"});
        return;
    }
    # Persist the product with a parameterized INSERT and unique-SKU handling.
    res.status(201);
    res.json({ok: true, sku: sku, name: name, price_cents: price, persisted: false});
}

func replace_product(req, res) {
    define sku = req.params.sku;
    # Validate every field and execute a parameterized UPDATE.
    res.json({ok: true, sku: sku, operation: "replace", persisted: false});
}

func delete_product(req, res) {
    define sku = req.params.sku;
    # Check permissions, references and business rules before deletion/archive.
    res.status(204);
    res.noContent();
}

server.get("/api/products", list_products);
server.get("/api/products/:sku", get_product);
server.post("/api/products", create_product);
server.put("/api/products/:sku", replace_product);
server.delete("/api/products/:sku", delete_product);
server.serve(".", 8080, {static: false});

In this server implementation, the request parser provides URL-encoded form parsing. Do not send a JSON body and expect req.form to decode it. The response serializer supports JSON values, including arrays and nested objects.

Static assets, files and downloads

When static serving is enabled, the server can serve files from its configured root. The index option selects the directory index filename. When static serving is disabled, only registered routes and explicit file helpers are available.

import server;

func home(req, res) {
    res.sendFile("public/home.html");
}

func stylesheet(req, res) {
    res.sendFile("public/assets/site.css");
}

func manual_download(req, res) {
    res.download("public/files/user-guide.pdf", "greenServeFE-guide.pdf");
}

server.get("/", home);
server.get("/assets/site.css", stylesheet);
server.get("/downloads/guide", manual_download);
server.serve(".", 8080, {
    host: "127.0.0.1",
    static: true,
    index: "index.html"
});

File helpers are rooted beneath the server's configured document root and apply path-safety checks. Keep private configuration, database files, uploaded files and TLS private keys outside publicly served directories. Never build a filesystem path directly from untrusted request text.

Outbound HTTP requests from the server module

The same module exports libcurl-backed client functions. They return an object with status, body, contentType, url, headers and error. The client enables TLS peer and hostname verification, follows at most five redirects, uses a 10-second connect timeout and a 30-second total timeout.

FunctionSignature
requestrequest(method, url, body?, headers?)
http_gethttp_get(url)
https_gethttps_get(url)
http_posthttp_post(url, body)
http_puthttp_put(url, body?, headers?)
http_patchhttp_patch(url, body?, headers?)
http_deletehttp_delete(url, body?, headers?)
http_optionshttp_options(url, body?, headers?)
import server;

func remote_status(req, res) {
    define result = server.http_get("https://example.com/");
    if (result.error != "") {
        res.status(502);
        res.json({ok: false, error: result.error});
        return;
    }
    res.json({
        ok: true,
        upstream_status: result.status,
        content_type: result.contentType,
        response_preview: result.body
    });
}

func submit_remote(req, res) {
    define headers = {"Content-Type": "application/json", "Accept": "application/json"};
    define result = server.request("POST", "https://api.example.com/events", "{\"event\":\"order.created\"}", headers);
    res.json({status: result.status, error: result.error, body: result.body});
}

server.get("/integrations/status", remote_status);
server.post("/integrations/events", submit_remote);
server.serve(".", 8080, {static: false});
Do not expose an arbitrary URL-fetching route to public users. That can create server-side request forgery (SSRF). Restrict upstream hosts to an explicit allowlist, validate every destination, avoid forwarding credentials, and set application-level response-size and time budgets.

HTTPS and listener options

The native listener supports TLS when built with its OpenSSL dependencies. Supply a certificate and matching private key. The listener uses a TCP socket, accepts connections, and handles each accepted connection in a forked child process.

import server;

func secure_home(req, res) {
    res.set("Strict-Transport-Security", "max-age=31536000");
    res.html("<h1>Secure greenServeFE site</h1>");
}

server.get("/", secure_home);
server.serve(".", 8443, {
    host: "0.0.0.0",
    protocol: "https",
    cert: "certs/fullchain.pem",
    key: "certs/private-key.pem",
    static: false,
    index: "index.html",
    backlog: 256,
    request_timeout: 15,
    max_requests: 0
});
OptionMeaningSource behavior
hostIPv4 bind addressDefault 0.0.0.0; * also binds all IPv4 interfaces.
protocolListener protocolhttps or tls enables TLS.
certPEM certificate pathRequired when TLS is enabled.
keyPEM private-key pathRequired and checked against the certificate.
indexDirectory index fileDefault index.html.
staticStatic file serving switchSet false when serving only explicit routes.
backlogSocket listen backlogDefault 1024; values below 1 are raised to 1.
max_requestsAccepted connection limitDefault 0, meaning no configured cap in this loop.
request_timeoutSocket read/write timeout in secondsDefault 15; clamped to 1–120 seconds.

The source currently exposes these options. Do not assume support for options that are not listed here, such as configurable rate limits, graceful shutdown hooks, compression settings, HTTP keep-alive tuning or request-body streaming.

Security, correctness and production readiness

Capabilities not claimed by this source: the inspected server.c listener does not establish a complete production framework with rate limiting, graceful shutdown APIs, response compression, WebSocket upgrades, streaming response bodies, request-body streaming or persistent keep-alive sessions. Do not document or depend on those as implemented features unless the C source and tests are extended to provide them.

Full native server export inventory

The module initializer registers the following top-level functions. This is the source-level export inventory for the inspected server.c.

ExportCategoryNotes
info()IntrospectionReturns module name, version and feature list.
request(method, url, body?, headers?)HTTP clientGeneric outbound request.
http_get(url)HTTP clientGET request.
https_get(url)HTTP clientGET helper; accepts HTTP or HTTPS URLs through the common client.
http_post(url, body)HTTP clientPOST request.
http_put(url, body?, headers?)HTTP clientPUT request.
http_patch(url, body?, headers?)HTTP clientPATCH request.
http_delete(url, body?, headers?)HTTP clientDELETE request.
http_options(url, body?, headers?)HTTP clientOPTIONS request.
read_file(path)File utilityReads a file as text; returns null on failure.
write_file(path, text)File utilityWrites text and returns a boolean success result.
render(template, data)TemplateRenders an inline template string with object substitutions.
url_encode(text)EncodingURL-encodes a string using libcurl.
json_escape(text)EncodingEscapes JSON string characters; this is not a complete JSON serializer.
get(path, handler)RoutingRegister GET handler.
page(path, html)RoutingRegister fixed HTML as a GET route.
post(path, handler)RoutingRegister POST handler.
put(path, handler)RoutingRegister PUT handler.
patch(path, handler)RoutingRegister PATCH handler.
delete(path, handler)RoutingRegister DELETE handler.
options(path, handler)RoutingRegister OPTIONS handler.
any(path, handler)RoutingRegister any-method handler.
use(prefix, handler)MiddlewareRegister prefix middleware; handler receives req, res and next.
clear_routes()RoutingClear all registered routes.
serve(root, port?, options?)ListenerStart the native HTTP or HTTPS listener.

Inspect capabilities at runtime

import server;

define details = server.info();
print(details.name);
print(details.version);
print(details.features);

func server_info_page(req, res) {
    res.json(server.info());
}

server.get("/server-info", server_info_page);
server.serve(".", 8080, {static: false});

The reported feature list in the inspected C source is: http-routing, route-parameters, middleware-chain, middleware-next, static-files, templates, json-responses, jsonp-responses, text-responses, file-downloads, form-parsing, cookie-parsing, response-cookies, cors, global-headers, security-headers, tls, http-client and request-timeouts. A feature label is a capability declaration, not a substitute for testing its behavior in the exact binary you deploy.

Further documentation and source

Back to greenServeFE documentation home