Xun
Web framework built on Go's built-in html/template and net/http package’s router. It is designed to be lightweight, fast, and easy to use while providing a simple and intuitive API for building web applications with advanced features such as middleware, routing, and template rendering
About Xun
This large README is shown as a plain-text preview. Read the full README at the source
# Xun
Xun is a web framework built on Go's built-in html/template and net/http package’s router. It is designed to be lightweight, fast, and easy to use. Xun provides a simple and intuitive API for building web applications, while also offering advanced features such as middleware, routing, and template rendering.
Xun [ʃʊn] (pronounced 'shoon'), derived from the Chinese character 迅, signifies being lightweight and fast.
[](https://github.com/yaitoo/xun/actions/workflows/tests.yml)
[](https://codecov.io/gh/yaitoo/xun)
[](https://goreportcard.com/report/github.com/yaitoo/xun)
[](https://pkg.go.dev/github.com/yaitoo/xun)
[](https://github.com/yaitoo/xun/releases)
[](LICENSE)
[](https://github.com/yaitoo/xun/compare)
## Features
- Works with Go's built-in `net/http.ServeMux` router that was introduced in 1.22. [Routing Enhancements for Go 1.22](https://go.dev/blog/routing-enhancements).
- Works with Go's built-in `html/template`. It is built-in support for Server-Side Rendering (SSR).
- Built-in response compression support for `gzip` and `deflate`.
- Built-in Form and Validate feature with i18n support.
- Built-in `AutoTLS` feature. It automatic SSL certificate issuance and renewal through Let's Encrypt and other ACME-based CAs
- Support Page Router in `StaticViewEngine` and `HtmlViewEngine`.
- Support multiple viewers by ViewEngines: `StaticViewEngine`, `JsonViewEngine` and `HtmlViewEngine`. You can feel free to add custom view engine, eg `XmlViewEngine`.
- Support to reload changed static files automatically in development environment.
- Built-in Content engine that renders `.md` files in `content/` as pages, deriving `Title` from the first `# H1` and `Description` from the first blockquote or top-level paragraph — no frontmatter, no separate template pipeline.
## Getting Started
> See full source code on [xun-examples](https://github.com/yaitoo/xun-examples)
### Install Xun
- install latest commit from `main` branch
```
go get github.com/yaitoo/xun@main
```
- install latest release
```
go get github.com/yaitoo/xun@latest
```
### Project structure
`Xun` has some specified directories that is used to organize code, routing and static assets.
- `public`: Static assets to be served.
- `components` A partial view that is shared between layouts/pages/views.
- `views`: An internal page view that can be referenced in `context.View` to render different UI for current routing.
- `layouts`: A layout is shared between multiple pages/views
- `pages`: A public page view that will create public page routing automatically.
- `text`: An internal text view that can be referenced in `context.View` to render with a data model.
- `content`: A Markdown-driven page tree. Every `.md` file auto-registers as `GET /<slug>`; paired `.tpl` files act as the bubble-up template (never registered as a route) and use the same `layouts/` directory as everything else. `.html` files in `content/` are independent page routes.
**NOTE: All html files(component,layout, view and page) will be parsed by [html/template](https://pkg.go.dev/html/template). You can feel free to use all built-in [Actions,Pipelines and Functions](https://pkg.go.dev/text/template), and your custom functions that is registered in `HtmlViewEngine`.**
### Layouts and Pages
`Xun` uses file-system based routing, meaning you can use folders and files to define routes. This section will guide you through how to create layouts and pages, and link between them.
#### Creating a page
A page is UI that is rendered on a specific route. To create a page, add a page file(.html) inside the `pages` directory. For example, to create an index page (`/`):
```
└── app
└── pages
└── index.html
```
> index.html
``` html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Xun-Admin</title>
</head>
<body>
<div id="app">hello world</div>
</body>
</html>
```
#### Creating a layout
A layout is UI that is shared between multiple pages/views.
You can create a layout(.html) file inside the `layouts` directory.
```
└── app
├── layouts
│ └── home.html
└── pages
└── index.html
```
> layouts/home.html
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Xun-Admin</title>
</head>
<body>
{{ block "content" .}} {{ end }}
</body>
</html>
```
> pages/index.html
```html
<!--layout:home-->
{{ define "content" }}
<div id="app">hello world</div>
{{ end }}
```
### Static assets
You can store static files, like images, fonts, js and css, under a directory called `public` in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).
**NOTE: `public/index.html` will be exposed by `/` instead of `/index.html`.**
#### Creating a component
A component is a partial view that is shared between multiple layouts/pages/views.
```
└── app
├── components
│ └── assets.html
├── layouts
│ └── home.html
├── pages
│ └── index.html
└── public
├── app.js
└── skin.css
```
> components/assets.html
```html
<link rel="stylesheet" href="/skin.css">
<script type="text/javascript" src="/app.js"></script>
```
> layouts/home.html
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Xun-Admin</title>
{{ block "components/assets" . }} {{ end }}
</head>
<body>
{{ block "content" .}} {{ end }}
</body>
</html>
```
### Text View
A text view is UI that is referenced in `context.View` to render the view with a data model.
**NOTE: Text files are parsed using the `text/template` package. This is different from the `html/template` package used in `pages/layouts/views/components`. While `text/template` is designed for generating textual output based on data, it does not automatically secure HTML output against certain attacks. Therefore, please ensure your output is safe to prevent code injection.**
#### Creating a text view
```
└── app
├── components
│ └── assets.html
├── layouts
│ └── home.html
├── pages
│ └── index.html
└── public
│ ├── app.js
│ └── skin.css
└── text
├── sitemap.xml
```
#### Render the view with a data model
```go
app.Get("/sitemap.xml", func(c *xun.Context) error {
return c.View(Sitemap{
LastMod: time.Now(),
}, "text/sitemap.xml") // use `text/sitemap.xml` as current Viewer to render
})
```
### Sitemap for blogs
Drop a `public/sitemap.xml` template next to your other static assets and the
framework serves `GET /sitemap.xml` with the URLs derived from your content
engine. No `text/sitemap.xml` indirection, no extra handler.
```
└── app
└── public
└── sitemap.xml
```
```xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{{ range .Data -}}
<url>
<loc>https://example.com{{ .Loc }}</loc>
{{ if .LastMod }}<lastmod>{{ .LastMod }}</lastmod>{{ end }}
</url>
{{ end -}}
</urlset>
```
`.Data` is `[]xun.SitemapURL{Loc, LastMod}` — by default projected from
`app.contentViews` only. The scope is intentionally narrow:
| Source | `Loc` | `LastMod` |
|--------|-------|-----------|
| `content/*.md` (with bubble-up template) | e.g. `content/post.md` → `/content/post` | file mtime (RFC3339) |
| `content/<dir>/index.md` | e.g. `content/blog/index.md` → `/blog/` (canonical trailing slash) | file mtime (RFC3339) |
Out of scope (by design — see `content_sitemap.go` doc comments for the
rationale):
- `pages/*.html` and `public/*.html` — user-authored, no mtime metadata
in the framework; add them to the sitemap by hand if needed.
- `app.Get` routes — classified as user handlers, not pages.
- Static assets in `public/` (CSS, JS, images, fonts, feeds).
- `.md` files without a bubble-up template (orphan entries — no route
to point crawlers at).
`Loc` is a URL path only (e.g. `/content/post`) — the framework does
not know which scheme + host your site is deployed under, so the
template prepends the host itself. Guard `LastMod` with
`{{ if .LastMod }}` (always safe; content views always carry a mtime
unless the source file lacks one).
#### Filtering
There is no `WithSitemap` option. Filtering happens in your `sitemap.xml`
template: drop entries by whatever signal is convenient in `Loc` /
`LastMod`, or write a custom handler that inspects `*ContentView` directly
via `app.contentViews`.
#### Adding your own URLs
`app.Sitemap(fn)` registers `GET /sitemap.xml` with your own builder — a
function that returns the entries to render. It runs per request, so it can
read a database, call another service, or depend on the request:
```go
app.Sitemap(func(c *xun.Context) ([]xun.SitemapURL, error) {
rows, err := db.QueryContext(c.Request.Context(), "SELECT slug, updated_at FROM posts")
if err != nil {
return nil, err
}
urls := make([]xun.SitemapURL, 0, len(rows))
for _, r := range rows {
urls = append(urls, xun.SitemapURL{
Loc: "/blog/" + r.Slug,
LastMod: r.UpdatedAt.Format(time.RFC3339), // LastMod is a string
})
}
return urls, nil
})
```
Several builders can be passed; their entries are concatenated in builder
order and de-duplicated by `Loc` (first occurrence wins). The order is not
re-sorted:
```go
app.Sitemap(contentBuilder, dbBuilder)
```
A builder that returns an error aborts the request with the framework's
standard error mapping (500 + `X-Log-Id`): a sitemap that silently misses
half of its URLs is worse than an error a crawler can retry.
Entries are passed through unchanged — the framework never resolves a host
or normalizes a path, so an absolute URL (`https://other.example/p/1`) is
rendered verbatim.
The template is parsed with `text/template`, which does **not** escape: a
`Loc` containing `&` or `<` lands in the document raw. Escape the values in
your template — or register an escaping helper with
`xun.WithTemplateFunc("xml", xml.EscapeText)` and call it from the template.
A sitemap file may hold at most 50,000 URLs (the protocol limit). The
framework enforces an effective cap of **40,000 URLs** — 80% of the limit —
on every document it serves: an over-cap document is truncated to the cap
and the dropped entries are logged with the total, the cap and the dropped
count.
Truncating is deliberate: a crawler rejects an oversized document *as a
whole*, so serving one loses every URL in it, not just the ones past the
limit. Keeping the first 40,000 keeps them indexable. The framework never
splits a document across several files — the builder owns the data, so
splitting is yours to arrange (see the sitemap index below).
The route answers 404 until a `public/sitemap.xml` template is published:
`app.Sitemap` does not require the file to exist.
#### Taking over the route
The framework registers `GET /sitemap.xml` itself, so a route you register
afterwards wins — either your own handler:
```go
app.Get("/sitemap.xml", func(c *xun.Context) error {
return c.View(c.App.SitemapURLs(), "sitemap.xml")
})
```
or `app.Sitemap(fn)` with your own builder. Replacing a route the framework
does not own (one registered through `app.Get` / `app.HandleFunc`) logs a
warning. The `TextViewer` is still exposed as `app.viewers["sitemap.xml"]`,
so you can reuse it — `c.View(data, "sitemap.xml")` renders the same
template with your own data.
Or write your own rendering entirely and ignore the viewer — the file is yours.
> curl --header "Accept: application/xml, text/xml,text/plain, */*" -v http://127.0.0.1/sitemap.xml
```bash
* Trying 127.0.0.1:80...
* Connected to 127.0.0.1 (127.0.0.1) port 80
> GET /sitemap.xml HTTP/1.1
> Host: 127.0.0.1
> User-Agent: curl/8.7.1
> Accept: application/xml, text/xml,text/plain, */*
>
* Request completely sent off
< HTTP/1.1 200 OK
< Date: Wed, 15 Jan 2025 11:51:56 GMT
< Content-Length: 277
< Content-Type: text/xml; charset=utf-8
<
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://github.com/yaitoo/xun</loc>
<lastmod>2025-01-15T19:51:56+08:00</lastmod>
<changefreq>hourly</changefreq>
<priority>1.0</priority>
</url>
* Connection #0 to host 127.0.0.1 left intact
</urlset>%
```
### Sitemap index
The protocol caps a document at 50,000 URLs. Anything larger is published as
a **sitemap index**: a `<sitemapindex>` document listing child sitemap files,
each of which stays within the limit.
`app.SitemapIndex(fn)` registers `GET /sitemap.xml` as the index document and
`GET /sitemaps/{name}` for the child files. `fn` is a `xun.SitemapIndexBuilder`
— a `func(c *xun.Context) ([]xun.SitemapGroup, error)` that returns the
groups, one named collection of URLs per child file:
```go
app.SitemapIndex(func(c *xun.Context) ([]xun.SitemapGroup, error) {
rows, err := db.QueryContext(c.Request.Context(),
"SELECT category, slug, updated_at FROM products ORDER BY category, id")
if err != nil {
return nil, err
}
defer rows.Close()
var out []xun.SitemapGroup
idx := map[string]int{}
for rows.Next() {
var cat, slug string
var updated time.Time
if err := rows.Scan(&cat, &slug, &updated); err != nil {
return nil, err
}
i, ok := idx[cat]
if !ok {
i = len(out)
idx[cat] = i
out = append(out, xun.SitemapGroup{Name: cat + ".xml"})
}
out[i].URLs = append(out[i].URLs, xun.SitemapURL{
Loc: "/p/" + slug,
LastMod: updated.UTC().Format(time.RFC3339),
})
}
return out, rows.Err()
})
```
This publishes `GET /sitemap.xml` listing `/sitemaps/shoes.xml`,
`/sitemaps/dresses.xml`, … and `GET /sitemaps/shoes.xml` serving that
category's URLs.
#### Templates
The index document is rendered from `public/sitemap-index.xml`, published as
the viewer `sitemap-index.xml` (parsed as `text/template`, like
`public/sitemap.xml`):
```
└── app
└── public
├── sitemap.xml
└── sitemap-index.xml
```
```xml
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{{ range .Data -}}
<sitemap>
<loc>https://example.com{{ .Loc }}</loc>
{{ if .LastMod }}<lastmod>{{ .LastMod }}</lastmod>{{ end }}
</sitemap>
{{ end -}}
</sitemapindex>
```
`.Data` is `[]xun.SitemapURL` — one row per group:
| Field | Value |
|-------|-------|
| `Loc` | the child's path: `/sitemaps/` + the URL-escaped group name |
| `LastMod` | the most recent `LastMod` among the group's URLs (empty when none carries one) |
The child files are rendered by the **existing** `public/sitemap.xml`
template — a child file is an ordinary `<urlset>` document, so no second
urlset template is needed:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{{ range .Data -}}
<url>
<loc>https://example.com{{ .Loc }}</loc>
{{ if .LastMod }}<lastmod>{{ .LastMod }}</lastmod>{{ end }}
</url>
{{ end -}}
</urlset>
```
As in the single-document mode, the template owns the scheme and host — the
framework does not know which host your site is deployed under.
#### Group names
The group name is the child file's name; the framework appends no extension
and no sequence number. The child file is served at `/sitemaps/` plus the
URL-escaped name, so a group named `女鞋` is listed as
`/sitemaps/%E5%A5%B3%E9%9E%8B` and served by that URL.
Two names need more than escaping: `.` and `..` are path segments the
server resolves away before routing, so their dots are escaped instead
(`/sitemaps/%2E`, `/sitemaps/%2E%2E`). A group without a name has no
addressable path and is skipped with a warning.
#### Collecting only the requested group
The builders run on every request — for the index document and for each child
file. `xun.SitemapGroupName(c)` tells the builder which group was asked for
(it is empty while the index document is rendered), so a builder can query
one group per request:
```go
app.SitemapIndex(func(c *xun.Context) ([]xun.SitemapGroup, error) {
name := xun.SitemapGroupName(c)
if name == "" {
// The index document: collect every group.
}
// ...
})
```
The hint is an optimization, not a contract: the framework always selects
the group by name, so a builder that ignores it still produces a correct
response — it only pays for the extra work.
#### Rules
- No builder → the content engine's entries (`app.SitemapURLs()`) as one
group named `content.xml`.
- Several builders → the groups are concatenated in builder order and
de-duplicated by name (first occurrence wins; a duplicate logs a warning).
- Each group's URLs are de-duplicated by `Loc` (first occurrence wins). The
de-duplication is per group: the same `Loc` in two groups is published in
both files.
- The 40,000-entry cap applies to each group and to the index's row count;
over-cap content is truncated and logged.
- A builder error aborts the request with the framework's standard error
mapping (500 + `X-Log-Id`).
- The index route answers 404 until `public/sitemap-index.xml` is published;
the child route answers 404 until `public/sitemap.xml` is published, and
for a name no group matches.
- `public/sitemap-index.xml` is published as a template, not as a static
file, and hot-reloads like `public/sitemap.xml`.
- `app.SitemapIndex` and `app.Sitemap` are not meant to be combined: the
later registration wins `GET /sitemap.xml`, and the index mode's child
routes stay registered (`http.ServeMux` cannot unregister a route).
- Registering the routes never panics. `http.ServeMux` panics on a
conflicting pattern, and its conflict rules are not exposed — a page at
`pages/{lang}/about.html` registers `GET /{lang}/about`, which conflicts
with the child route. The registration is defensive: a conflict skips the
route and logs a warning.
### Content
The Content engine turns Markdown files into pages without introducing a new `Viewer` or a second template engine. Drop a `.md` file into `content/` and it auto-registers as `GET /<slug>`; drop a `.tpl` next to it (or any ancestor `index.tpl`) to control how the rendered Markdown is wrapped.
`.html` and `.tpl` inside `content/` have distinct roles:
- `.tpl` — bubble-up template only. Loaded into the template graph; never registered as a route.
- `.html` — page route only. Registered as a route; never consulted during bubble-up.
This is what lets a directory such as `content/blog/` hold both `index.tpl` (wrapping template) and `index.md` (real Markdown page) without conflict.
#### Directory layout
```
└── app
├── layouts
│ └── site.html
└── content
├── hello.md ← GET /hello
├── hello.tpl ← optional, dedicated template for /hello
└── 2026
├── index.tpl ← bubble-up target (not a route)
├── index.md ← optional, directory-level page: GET /2026/
└── deeper.md ← GET /2026/deeper
```
For each `.md` file, the engine looks for a bubble-up template in this order:
1. `content/<slug>.tpl`
2. `content/<dir>/index.tpl`
3. any ancestor `index.tpl`
4. the root `index.tpl`
Frequently Asked Questions
What is Xun?
Xun is a Web Frameworks library for the Go programming language. Web framework built on Go's built-in html/template and net/http package’s router. It is designed to be lightweight, fast, and easy to use while providing a simple and intuitive API for building web applications with advanced features such as middleware, routing, and template rendering
How do I install Xun?
Install Xun with the Go module system using `go get yaitoo/xun`. Check the repository for the current installation instructions.
What category does Xun belong to?
Xun is listed under Web Frameworks, specifically Web Frameworks.