# infogulch/xtemplate architecture

> Architecture diagram of the GitHub repository infogulch/xtemplate, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-11). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/infogulch/xtemplate
- Repository: https://github.com/infogulch/xtemplate

## Overview

##### Project type and purpose
- **Project Type:** Open-source Go library plus CLI/web server tool
- **Purpose:** Provide an in-memory, reloadable, html/template–based web server (“xtemplate”) that maps filesystem templates to HTTP routes, injects pluggable data sources (DB, FS, NATS, KV), and serves static assets efficiently.

##### File structure
- **Top-level artifacts:**
- cmd/main.go: the reference CLI that builds and runs an xtemplate Server
- config.go, server.go, instance.go: core library entrypoints
- handlers.go, build.go, dot_*.go: template loader, request handlers, and dot-provider implementations
- test/: end-to-end tests, migrations, templates, hurl scripts
- app/: example application showing how to wire xtemplate in code
- **Patterns and conventions:**
- Package layout follows library (root) + cmd + example + test
- Dot-provider pattern for pluggable context fields (DotDB, DotFS, DotNATS, DotKV)
- Build scripts (build.go, make_tool.cue) for codegen / releases

##### Key insights from README
- **Architecture highlights:**
- At startup, templates are parsed once and kept in memory
- A reloadable Server wraps an immutable Instance (http.Handler) that routes requests
- Routes are derived from template filenames or `define` directives
- Dot context provides request-scoped fields and custom data-source APIs
- Built-in providers: database/sql, filesystem, NATS, key-value store
- CLI flags allow embedding templates, watching files, adjusting delimiters, etc.

##### Main components and interactions (
a. **xtemplate CLI / Caddy plugin** (cmd/main.go / external Caddy module)
– Reads flags / config → builds a `xtemplate.Config`
→ calls `Config.Server()` → obtains a reloadable `Server` (implements `http.Handler`)
→ passed to Go’s `http.ListenAndServe` or Caddy
b. **Server** (server.go)
– Wraps an atomic pointer to the current `Instance`
– Exposes `.Reload()` to regenerate a new Instance on template or config change
c. **Instance** (instance.go)
– Implements `http.Handler`
– On initialization, walks `templates/` directory → parses every `.html` file
– Builds a `http.ServeMux` mapping file paths or `define "METHOD /path"` names to handlers
– Precomputes static-asset hashes (gzip, brotli) for efficient caching
d. **ServeMux & Handlers** (handlers.go)
– **TemplateHandler:** invokes `html/template` with a `DotContext` for dynamic pages
– **StaticHandler:** serves non-template assets with negotiated encoding and cache headers
– **SSEHandler:** streams Server-Sent Events by invoking a template with `.Flush`
e. **DotContext & Providers** (dot_*.go)
– Core fields: `.X` (Instance metadata), `.Req` (request wrapper), `.Resp` (response control), `.Flush` (SSE)
– Optional providers wired via `Config.ContextProviders`:
- DotDB: run SQL queries / Exec
- DotFS: list/read files
- DotNATS: publish/request via NATS
- DotKV: read static key-value data
– Each provider’s `Value(req)` returns a per-request object available in templates
f. **html/template + FuncMaps**
– Templates execute with built-in and Sprig functions + xtemplate’s custom helpers (markdown, sanitize, trustHtml)
g. **Tests & Examples**
– test/ directory uses hurl scripts to exercise routing, FS, DB, flags, SSE, NATS
– app/ directory shows embedding xtemplate in a standalone Go app

##### Architectural patterns & design principles
- **Separation of concerns:**
- CLI vs. Server vs. Instance vs. Handlers vs. DotProviders
- **Immutable instances + hot reload:** atomic swap of request handler
- **Convention-over-configuration:** filesystem → routes mapping
- **Provider pattern:** inject dynamic capabilities into templates without recompilation
- **Single binary deployment:** templates on disk or embed via Go’s `embed`

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Client Layer
    subgraph "Client Layer"
        Client["Browser/API Client"]:::external
    end

    %% CLI Layer
    subgraph "CLI Layer"
        CLI["xtemplate CLI / Caddy plugin"]:::cli
        Config["xtemplate.Config"]:::code
    end

    %% Server/Instance Layer
    subgraph "Server/Instance Layer"
        Server["Server<br/>(server.go)"]:::runtime
        Instance["Instance<br/>(instance.go)"]:::runtime
    end

    %% Template Layer
    subgraph "Template Layer"
        ServeMux["http.ServeMux"]:::runtime
        TH["TemplateHandler"]:::runtime
        SH["StaticHandler"]:::runtime
        SSE["SSEHandler"]:::runtime
    end

    %% Context Layer
    subgraph "Context Layer"
        DotContext["DotContext<br/>(dot.go)"]:::code
        DotReq["Req<br/>(dot_req.go)"]:::code
        DotResp["Resp<br/>(dot_resp.go)"]:::code
        DotFlush["Flush<br/>(dot_flush.go)"]:::code
        subgraph "Providers"
            PDB["DotDB<br/>(dot_db.go)"]:::code
            PDBCfg["DotDB Config<br/>(dot_db_config.go)"]:::code
            PFS["DotFS<br/>(dot_fs.go)"]:::code
            PFSCfg["DotFS Config<br/>(dot_fs_config.go)"]:::code
            PNATS["DotNATS<br/>(dot_nats.go)"]:::code
            PNATSCfg["DotNATS Config<br/>(dot_nats_config.go)"]:::code
            PKV["DotKV<br/>(dot_kv.go)"]:::code
            PFlags["DotFlags<br/>(dot_flags.go)"]:::code
            PInst["DotInstance<br/>(dot_instance.go)"]:::code
        end
    end

    %% Template Engine
    HT["html/template + FuncMap<br/>(funcs.go, frontmatter.go)"]:::code

    %% Data Layer
    subgraph "Data Layer"
        DB["Database"]:::external
        FSys["Filesystem"]:::external
        NATS["NATS"]:::external
        KV["Key-Value Store"]:::external
    end

    %% Examples & Tests
    subgraph "Examples & Tests"
        App["Example App<br/>(app/app.go)"]:::code
        Tests["E2E Tests<br/>(test/)"]:::code
    end

    %% Connections
    Client -->|"GET /... HTTP"| Server
    CLI -->|"reads flags/config"| Config
    Config -->|"Config.Server()"| Server
    Server -->|"ListenAndServe"| Client
    Server -.reload.-> Instance
    Instance -->|"build routes"| ServeMux
    ServeMux -->|"route to"| TH
    ServeMux -->|"route to"| SH
    ServeMux -->|"route to"| SSE
    TH -->|"template.Execute"| HT
    TH -->|"inject"| DotContext
    SH -->|"serve static"| FSys
    SSE -->|"stream SSE"| HT
    DotContext --> DotReq
    DotContext --> DotResp
    DotContext --> DotFlush
    DotContext -->|"wire"| PDB
    DotContext -->|"wire"| PFS
    DotContext -->|"wire"| PNATS
    DotContext -->|"wire"| PKV
    DotContext -->|"wire"| PFlags
    DotContext -->|"wire"| PInst
    PDB -->|"Exec SQL"| DB
    PFS -->|"Read/List"| FSys
    PNATS -->|"Publish/Request"| NATS
    PKV -->|"Get KV"| KV

    %% Click Events
    click CLI "https://github.com/infogulch/xtemplate/blob/master/cmd/main.go"
    click Config "https://github.com/infogulch/xtemplate/blob/master/config.go"
    click Server "https://github.com/infogulch/xtemplate/blob/master/server.go"
    click Instance "https://github.com/infogulch/xtemplate/blob/master/instance.go"
    click ServeMux "https://github.com/infogulch/xtemplate/blob/master/handlers.go"
    click TH "https://github.com/infogulch/xtemplate/blob/master/handlers.go"
    click SH "https://github.com/infogulch/xtemplate/blob/master/handlers.go"
    click SSE "https://github.com/infogulch/xtemplate/blob/master/handlers.go"
    click DotContext "https://github.com/infogulch/xtemplate/blob/master/dot.go"
    click DotReq "https://github.com/infogulch/xtemplate/blob/master/dot_req.go"
    click DotResp "https://github.com/infogulch/xtemplate/blob/master/dot_resp.go"
    click DotFlush "https://github.com/infogulch/xtemplate/blob/master/dot_flush.go"
    click PDB "https://github.com/infogulch/xtemplate/blob/master/dot_db.go"
    click PDBCfg "https://github.com/infogulch/xtemplate/blob/master/dot_db_config.go"
    click PFS "https://github.com/infogulch/xtemplate/blob/master/dot_fs.go"
    click PFSCfg "https://github.com/infogulch/xtemplate/blob/master/dot_fs_config.go"
    click PNATS "https://github.com/infogulch/xtemplate/blob/master/dot_nats.go"
    click PNATSCfg "https://github.com/infogulch/xtemplate/blob/master/dot_nats_config.go"
    click PKV "https://github.com/infogulch/xtemplate/blob/master/dot_kv.go"
    click PFlags "https://github.com/infogulch/xtemplate/blob/master/dot_flags.go"
    click PInst "https://github.com/infogulch/xtemplate/blob/master/dot_instance.go"
    click HT "https://github.com/infogulch/xtemplate/blob/master/funcs.go"
    click HT "https://github.com/infogulch/xtemplate/blob/master/frontmatter.go"
    click App "https://github.com/infogulch/xtemplate/blob/master/app/app.go"
    click Tests "https://github.com/infogulch/xtemplate/tree/master/test/"

    %% Styles
    classDef cli fill:#BBDEFB,stroke:#0D47A1
    classDef code fill:#BBDEFB,stroke:#0D47A1
    classDef runtime fill:#C8E6C9,stroke:#1B5E20
    classDef external fill:#FFE0B2,stroke:#E65100
```
