Menu
Learn
Overview Introduction 50 Dimensions Tutorial Snippets vs Other Languages
Build
Editor Playground Compiler API
Docs
Language Spec Formats u keyword Dataframe Python AI Library Feature Status Packages What's Implemented
Platform
Server About Transpilation Web & Templates
Safebox
Why U Analysis Engine Comparison Possibilities
Overview Architecture Native .u PHP Tree-shaking Features Real-time Mesh Binary Start

U WebServer

A production HTTP server written entirely in U. Compiles to a single native binary via U → C → gcc. Serves PHP apps, native .u handlers, WebSocket rooms, SSE streams, TLS, image processing, a live dashboard, and an encrypted mesh — all in one process, no dependencies.

u2c webserver_u/src/main.u -o userver
./userver --port=8080 --root=./web
Source → Try U Online

Why another web server?

Most web servers are written in C with configuration files on top. The U webserver is written in U, so the configuration, the routing, the handlers, and the server itself are all the same language — and the whole thing compiles to a single binary.

The webserver is a port of the Qbix PHP webserver to pure U. It keeps every capability of the original — PHP execution, COW forking, WebSocket rooms, distributed mesh — and adds native .u handlers that bypass the PHP layer entirely. When you don't need PHP at all, the binary is smaller, faster, and has zero runtime dependencies.

29.u source modules
1binary output
0runtime deps
18built-in features

Architecture

The server is structured as a set of U modules compiled into a single binary. The event loop accepts connections, the router dispatches to handlers, and each handler chain (.u, .php, static, proxy) runs in order until one matches.

// main.u — the dispatch chain // 1. WebSocket upgrade // 2. SSE stream // 3. Built-in endpoints (/health, /Q/dashboard) // 4. ACME challenges // 5. Proxy upstreams // 6. Response cache // 7. Route table (custom handlers) // 8. Image processing (?w=400) // 9. PHP handler (.php → transpile → compile → dlopen) // 9b. U handler (.u → compile → dlopen) // 10. Pre-compressed static (gzip/brotli) // 11. Static files (ETag, 304, MIME)

Each handler resolves independently. The PHP handler transpiles .php to .u to .c to a shared library, then dlopen/dlsym to execute it. The native .u handler does the same but skips the PHP transpilation step — it goes directly from .u to .c to .so.

Native .u Handlers

Drop a .u file in your document root and the server compiles and loads it on first request. No PHP, no transpiler, no interpreter — just U compiled to native code.

// web/api/hello.u — a native handler o "./http" f handle(req: HttpReq) -> HttpResp name = req.query.get("name") ?? "world" r => HttpResp({ status: 200, headers: { "Content-Type": "application/json" }, body: "{\"hello\": \"" + name + "\"}" })

The handler exports a handle(req: HttpReq) -> HttpResp function. The server compiles it with u2c (U → C), then gcc with -ffunction-sections -fdata-sections and links with --gc-sections to strip unused code. The compiled .so is cached and reloaded only when the source file changes.

You can mix .u and .php files in the same document root. The server checks the extension and dispatches to the right handler. This lets you migrate PHP endpoints to native U one file at a time.

⚡

Compile on demand

First request compiles the handler to a shared library. Subsequent requests use the cached .so. Source changes trigger recompilation automatically.

🎯

Direct dispatch

Native handlers receive an HttpReq and return an HttpResp. No SAPI layer, no output buffering, no session machinery — just a function call through a pointer.

📦

Mixed routing

Drop .u files alongside .php files. The server handles both. Migrate endpoints incrementally or run a pure-U server with no PHP at all.

PHP Compatibility

The server runs existing PHP apps via a transpile-on-demand pipeline. PHP files are transpiled to U, compiled to native code, and executed through the PhpSAPI layer that provides the familiar PHP runtime environment.

The pipeline: .php → transpiler (JS or Python) → .u → u2c → .c → gcc → .so → dlopen. The transpiler rewrites PHP's global functions (header(), session_start(), setcookie()) to use the explicit SAPI parameter, so they work correctly in a shared-process server.

See the PHP compatibility page for the full function list, framework support, and migration guide.

Tree-shaking & Binary Size

U's compiler and the C toolchain work together to keep binaries small. Only the stdlib functions your code actually calls are linked into the final binary.

The optimization happens at three levels:

1. Conditional I/O headers

The u2c compiler tracks which stdlib namespaces your program uses. If you never call Network.listen(), the generated C never includes u_net.h (which pulls in pthread). If you never touch the filesystem, u_fs.h is omitted. This means a handler that only does string processing doesn't link against the networking stack at all.

2. Binding-level selection

The stdlib binding table (stdlib_bind.py) maps U stdlib functions to C implementations. Only bindings that are actually called in your program generate code. A handler that calls Files.read() and Files.write() gets those two C implementations and nothing else from the filesystem module.

3. Linker dead-code elimination

Native .u handlers compile with -ffunction-sections -fdata-sections and link with -Wl,--gc-sections. This tells gcc to put each function and data object in its own section, then strip any section the linker can prove is unreachable. Combined with -O2, this removes unused stdlib functions, unused struct definitions, and unused constant tables from the final binary.

For the full webserver binary (all 29 modules), most of the stdlib is used, so the savings are modest. For a standalone .u handler compiled as a separate shared library, the difference is significant — a hello-world handler compiles to a few KB.

Handler typePipelineStdlib includedRelative size
Full webserver binaryU → C → gcc → ELFMost (29 modules use most namespaces)Baseline
Native .u handler (.so)U → C → gcc -ffunction-sections → .soOnly what the handler callsSmall
PHP handler (.so)PHP → U → C → gcc → .soHandler code + PhpSAPI + PhpCompatMedium

Feature Set

Everything runs in one process. No nginx, no Redis, no Node, no Docker.

🌐

Static Files

ETag from mtime+size, If-None-Match → 304, directory index, MIME detection for 30+ types, blocked prefixes (/. and /_).

🖼️

Image Processing

Resize with ?w=400. Serves AVIF or WebP from Accept header. Save-Data support. Disk cache that regenerates on source change.

🔒

TLS & ACME

HTTPS auto-starts when certs exist. Built-in ACME client for Let's Encrypt auto-renewal. HTTP/2 support via h2 module.

📊

Live Dashboard

Built-in at /Q/dashboard. Requests per minute, connections, latency, memory, per-path stats. No Grafana needed.

🚀

Response Cache

In-memory cache with configurable slots and TTL. Small responses cached automatically. Cache-Control headers respected.

🔧

Reverse Proxy

Forward matching paths to upstream backends. Health checks, timeouts, automatic failover.

📦

Pre-compression

Pre-compresses static assets with gzip and brotli at startup. Serves compressed versions when Accept-Encoding matches.

⚙️

JSON Config

Configure via CLI args or a JSON file. Port, host, root, cache size, routes, TLS certs, proxy upstreams — all in one place.

WebSocket & SSE

Real-time on the same port as HTTP. No Node.js, no Socket.IO server, no separate process.

WebSocket upgrade is detected before the HTTP dispatch chain. Rooms are first-class: join a room, broadcast to it, send to a specific connection. The SSE manager handles long-lived connections for server-sent events. Both are managed by the transport layer.

// WebSocket upgrade is automatic // Client connects to ws://localhost:8080/chat // Server detects the upgrade header and hands off to the transport layer // Rooms, broadcast, and per-connection messaging built in

Encrypted Mesh

Every U WebServer has a cryptographic identity and can discover other servers nearby over Bluetooth and Wi-Fi. Apps keep working offline.

🌐

Discovery

BLE and Wi-Fi peer discovery. Servers find each other without a central registry. Distance-vector routing with multi-hop relay.

🔒

Encryption

ECDH handshake, AES-256-GCM sessions. End-to-end encrypted. No server in the middle.

🔄

Data Sync

Bloom filter exchange finds differences. Prolly tree comparison for large datasets. Pluggable conflict resolution.

Single Binary

The entire server compiles to one native binary. No PHP interpreter, no runtime, no Docker image — just copy and run.

# Build the server u2c webserver_u/src/main.u -o userver # Or build with Cosmopolitan for a portable binary # (runs on Linux, macOS, Windows, FreeBSD from one file) u2c webserver_u/src/main.u -o userver --cosmo

The binary includes all 29 modules: HTTP, routing, PHP handler, native .u handler, WebSocket, SSE, TLS, ACME, image processing, dashboard, pre-compression, reverse proxy, mesh networking, cluster replication, and discovery. If you don't need a feature, the linker strips its unused code paths.

Getting Started

# 1. Clone the repo git clone https://github.com/ULanguageOrg/webserver cd webserver # 2. Build the server u2c webserver_u/src/main.u -o userver # 3. Create a handler mkdir -p web/api cat > web/api/hello.u <<'EOF' o "./http" f handle(req: HttpReq) -> HttpResp r => HttpResp({ status: 200, headers: { "Content-Type": "text/plain" }, body: "Hello from U!" }) EOF # 4. Run ./userver --port=8080 --root=./web # 5. Test curl http://localhost:8080/api/hello.u

The server compiles the .u handler on first request, caches the shared library, and serves subsequent requests from the cached binary. Change the source file and the next request recompiles automatically.