⚙️ Backend Extensions & Ops
Last updated:2026-11-25
⚙️ Admin Extensions and Operations
This chapter summarizes the CMS’s admin extension capabilities and operations tools: configuration parameters (8 groups), search engine proactive push, WebAPI, security configuration, system update, plus external event Webhook, hook bus extension points, media library, backup and restore, audit log, translation status check, and batch add / delete. The first four are newly added admin capabilities (entries unified under the “Configuration” and “System Settings” groups); they directly affect front-end links and titles, so template developers should know them too.
🔔 External Event Webhook
Content lifecycle events (create / update / delete) are broadcast through the event bus and can be pushed to external systems (e.g. search indexing, CDN refresh, WeCom bots). Automatically enabled once the following environment variables are configured; with none configured it is a zero-overhead no-op.
📍 Environment Variables
| Variable | Description |
|---|---|
CMS_WEBHOOK_URLS |
Target addresses, comma-separated, e.g. https://a.com/hook,https://b.com/x |
CMS_WEBHOOK_EVENTS |
Subscribed event whitelist, comma-separated; omitted or containing * means receiving all |
Event types: content.created / content.updated / content.deleted / system.media.deleted / system.backup.restored. System-level events (media deletion, backup restore) uniformly carry the system. prefix — CMS_WEBHOOK_EVENTS must use the full prefix (e.g. system.media.deleted) to match; writing only media.deleted will never match. Pushes are async POST with automatic retry; example body:
POST {address from CMS_WEBHOOK_URLS}
Content-Type: application/json
{
"type": "content.created",
"payload": {
"content_type": "post", // post / product / case / page
"content_id": 11896,
"site_id": 1,
"actor": "admin",
"ip": "127.0.0.1",
"timestamp": "2026-08-24T17:41:02+08:00"
}
}
🧩 Extension Points / Hook Bus
The system has a built-in in-process event bus (internal/hooks), on which the Webhook is implemented. Developers can register custom hooks or custom routes without modifying core code.
// Broadcast a content event (already called in each content save/delete handler)
hooks.FireContentEvent(action, contentType string, id, siteID int, actor, ip string)
// action: "created" | "updated" | "deleted" | "published"
// Register a custom hook (receives all events)
hooks.RegisterHook(func(evt hooks.Event) { /* custom logic */ })
// Register a custom route (mounted during startup ApplyRouteRegistrars)
hooks.RegisterRouteRegistrar(func(r *gin.Engine) {
r.GET("/my-plugin", myHandler)
})
Custom template functions: once registered in GetTemplateFuncs, they become available to front-end templates; note that functions must be pre-declared in the template function table — template calls to unregistered function names are not possible.
🖼️ Media Library
📍 Menu and APIs
| Entry | Description |
|---|---|
Admin → Media Library (/admin/media) |
Lists all files under static/uploads/ (images auto-detected with is_image, extension ext) |
GET /admin/media/api |
Returns a JSON file listing (files: [{path, size, ext, is_image, modified}]) |
POST /admin/media/delete |
Form field path=/static/uploads/xxx, deletes the specified file and records an audit entry |
Deletion only removes the file; references to that image in articles are not automatically removed. Confirm there are no body references before deleting.
💾 Backup and Restore
One-click export / import of all content (built-in tables + custom model tables), JSON format, dialect-safe (restorable on SQLite / MySQL / PostgreSQL alike).
📍 Entries
| Entry | Description |
|---|---|
Admin → Backup and Restore (/admin/backup) |
The page provides export / import buttons |
GET /admin/backup/export |
Downloads cms-backup-<timestamp>.json (content data JSON) |
GET /admin/backup/sqlite |
SQLite deployments only: downloads the full physical database file cms-sqlite-backup-<timestamp>.db |
POST /admin/backup/restore |
Form field file uploads JSON for restore (upsert table by table) |
🗄️ SQLite Full Database Backup: when the current database dialect is SQLite, the backup page additionally offers a “Download Backup (.db full database)” button (API GET /admin/backup/sqlite?download=1). It takes an instant consistent snapshot of the current site’s database file (first runs VACUUM INTO to produce a temporary copy, then streams the download and deletes the temp file), yielding an SQLite physical file identical to production and directly reopenable by the program — as opposed to the “content data JSON” above.
- Use cases: whole-machine / file-level migration, backing up together with settings/users/audit and all other tables, or wanting to open and inspect it directly with a database tool.
- Non-SQLite environments (MySQL / PostgreSQL): the button is not shown, and the API directly returns 400; use the JSON backup above.
- Scope note: like the JSON backup, it does not include real media files under uploads/; media files must be backed up separately via filesystem / image-level means.
Multi-tenant (SaaS) mode caution: the site database file name is randomly generated at provisioning time (e.g. 9f3k2m1pq4rx.db),
and all tenants share one engine process. Platform-side automatic backups are written per tenant database into that tenant’s backups/ directory,
not just the shared engine’s empty database; for full-database restore, target “the actual .db under that tenant’s directory”,
not the name cms.db.
Export structure: { version, exported_at, dialect, tables: { table: [ row objects... ] } }; all row fields are normalized to strings for cross-dialect restore. Restore updates existing records by primary key / unique key.
📏 The backup page shows “current backup data size” (e.g. 1.23 MB), which is the size of the JSON content body about to be exported — i.e. the byte count after serializing all content table records, as a data-volume estimate. It is not the size of the cms.db file on disk and does not include real images / videos uploaded to uploads/ (only their database records).
📝 Audit Log
Records key operations (logins, content CRUD, media deletion, backup restore) for security traceability.
📍 Entries
| Entry | Description |
|---|---|
Admin → Audit Log (/admin/audit) |
Audit list page |
GET /admin/api/audit |
JSON list: logs: [{id, action, actor, target_type, target_id, detail, ip, site_id, created_at}] |
Recorded action examples: auth.login / auth.login_fail / content.created / content.updated / content.deleted / media.deleted / backup.restored. Note that audit actions themselves do not carry the system. prefix (that prefix appears only on Webhook push event types). In code, append records with RecordAudit(siteID, actor, action, targetType, targetID, detail, ip) or the convenience method RecordContentAudit(c, action, ct, id).
📥 Batch Add / Delete
The admin provides batch operations for the five content types: Article / Product / Case / Single Page / Category: list pages support multi-select and one-click deletion, plus a dedicated “Batch Add” page that creates multiple entries at once. All batch deletions are site-isolated (only current-site data is deleted), consistent with single-item deletion.
📍 Entries and APIs
| Entry | Description |
|---|---|
| Each content list page (articles / products / cases / single pages / categories) | Each row gets a checkbox; the list top has “Batch Add” and “Delete Selected” buttons (with select-all, selection count, double confirmation) |
GET /admin/{type}/batch |
Batch add page ({type} ∈ posts / products / cases / pages / categories; categories corresponds to “categories”) |
POST /admin/{type}/batch-save |
Batch save: form fields are arrays (e.g. title[] / name[]); batch creation under the same category and status; rows with empty title / name are skipped automatically |
POST /admin/{type}/batch-delete |
Batch delete: form field ids (multi-select); deletes in one go; irreversible — confirm before submitting |
The batch add page supports two entry methods: ① fill in row by row in the table (title / name, summary, category, price, status, etc.); ② paste one title / name per line into the “Quick Import” textbox and convert to rows in one click (products / cases / categories can also specify “import to category / parent category”). When the category URL identifier or the single page slug is left blank, the system auto-fills it with the record number.
📄 New admin template partials: templates/admin/partials/posts_batch.html / products_batch.html / cases_batch.html / pages_batch.html / categories_batch.html. List pages posts_list.html / products_list.html / cases_list.html / pages_list.html (categories are rendered inline in AdminCategories) have each added checkboxes and a batch-delete form.
- Site isolation: batch delete goes through repo.Delete(id, siteID) (articles / products / cases / categories) or DELETE ... WHERE id=? AND site_id=? (single pages), affecting only the current admin site.
- No cascading: batch-deleting a category does not automatically cascade-delete its child categories or content (consistent with single-item deletion); handle children first before deleting.
- Irreversible: batch delete is a hard delete; confirm the checked items before operating, and back up first if necessary.
🌐 Translation Status Check
Compares the same content tables between the source site and the target site, listing items “missing on the target site” or “with an empty target title” that are pending translation.
Entry: Admin → Translation Status Check (/admin/i18n). Query parameters: type (posts / products / cases / pages), src (source site ID), dst (target site ID). The page shows source / target counts and the pending-translation list (with content ID, Code/Slug, title, and the reason it’s missing).
📦 Static Space Publishing (Split by File Category)
The admin “Publish” page supports distributing the static site to multiple self-selected spaces, with each space declaring which category of files it handles:
| File Category | Content |
|---|---|
html |
HTML pages (including protocol files such as robots / sitemap) |
assets |
Theme static assets (css / js / images / fonts under static/ excluding uploads) |
uploads |
Attachments (user-uploaded content under static/uploads/) |
This enables combinations like “HTML on an overseas ICP-free space, attachments kept on a domestic one to save money”. The whole target configuration is stored as JSON under the deploy_targets key in settings (same approach as ai_models, no schema migration needed).
📍 Supported Space Types (8, providerSpecs)
| Type | Name | Overseas | Key Configuration |
|---|---|---|---|
cfpages |
Cloudflare Pages | ✅ | Account ID / project name / API Token / branch |
netlify |
Netlify | ✅ | Site ID / Access Token |
github |
GitHub Pages | ✅ | Repo owner / repo / publish branch / Token / subdirectory |
r2 |
Cloudflare R2 | ✅ | S3 Endpoint / Bucket / AK / SK / in-bucket prefix |
s3 |
S3-compatible storage | Endpoint / Bucket / Region / AK / SK / prefix / path style | |
cos |
Tencent Cloud COS | SecretId / SecretKey / Bucket / Region / prefix | |
webdav |
WebDAV | WebDAV address / username / password | |
ftp |
FTP | Host / port / account / password / remote directory |
The S3 family (
r2/s3) shares one implementation: a hand-written AWS Signature V4 using only the standard library, zero external SDK dependencies (seeinternal/handlers/deploy_s3.go). Cloudflare R2 / MinIO / Qiniu etc. all go through this channel, differing only in Endpoint, Region, and whether path style (path_style) is used. Google Cloud Storage / Azure Blob Storage have no dedicated implementation — to integrate, use their S3-compatible (interoperability) endpoints and configure as “S3-compatible storage”.
📍 Routes
| Method | Path | Description |
|---|---|---|
| GET | /admin/deploy |
Publish page (generation block + target configs + connectivity test) |
| POST | /admin/deploy/config |
Save channel-level configuration |
| POST | /admin/deploy/ftp /edgeone /git /cos /s3 /webdav |
Publish per channel |
| POST | /admin/deploy/git/add /git/delete |
Maintain the Git repository list |
| POST | /admin/deploy/run |
Publish to all configured targets |
| POST | /admin/deploy/test |
Connectivity test (read-only probe, writes no files) |
| POST | /admin/deploy/targets/save /targets/delete |
Add / edit / delete “static space” targets |
Besides the 8 space types above, there are two more independent publishing channels: EdgeOne and Git repositories. Related implementations:
deploy_targets.go(space definitions and file-category splitting),deploy_s3.go(SigV4 upload),deploy_webdav.go(WebDAV),deploy_conn.go(connectivity test),deploy_handlers.go(publish page and channel entries).
🎛️ Configuration Parameters (Admin → Configuration)
The new unified configuration entry (/admin/config) consolidates site-level switches previously scattered across places into 8 tabs, all saveable and editable. Except “Basic Configuration” which writes the sites table directly, everything else is stored uniformly in the settings table (key/value); the save API is POST /admin/config/save (persisted per tab).
📍 The 8 Tabs and Their Settings
| Tab | Description | Main settings (settings key) |
|---|---|---|
| Basic Configuration | Site title / domain / Logo / ICP filing / analytics / template directory etc., reuses /admin/site/save |
— (writes the sites table) |
| Baidu API | Baidu Webmaster platform proactive push (normal inclusion) | baidu_enabled / baidu_site / baidu_token / baidu_auto_push |
| IndexNow Push | One submission reaches Bing / Yandex / Seznam / Naver at once | indexnow_enabled / indexnow_key / indexnow_endpoint / indexnow_key_location / indexnow_auto_push |
| WebAPI | External read-only JSON API (see next section) | webapi_enabled / webapi_token / webapi_allow_ip / webapi_limit |
| Security Configuration | Login failure lockout / admin IP whitelist / session policy / upload blacklist | sec_login_fail_limit / sec_login_lock_minutes / sec_idle_timeout / sec_session_ip_bind / sec_admin_ip_whitelist / sec_upload_ext_blacklist |
| URL Rules | Detail page suffix, naming (ID / alias), pagination style — affects all front-end {{.URL}} |
url_detail_suffix / url_detail_name / url_page_style |
| Title Style | Title separator and order, home page title template, auto-summary length — affects front-end {{.PageTitle}} |
seo_title_sep / seo_title_order / seo_home_title / seo_desc_len |
| Remote Attachment Configuration | Reuses the existing remote attachment form and save API | Same as the original “Remote Attachment” settings |
After changing “URL Rules”, the static site must be regenerated for the HTML files on disk to take effect (dynamic pages take effect immediately); seo_desc_len (auto-summary length) affects the default truncation length for content without a manually filled summary (lists / {{.Summary}}).
🌐 WebAPI (External Read-only JSON API)
The built-in external read-only API (GET only, returns only published content with status=1), which has replaced the legacy /api/v1/posts series APIs. The switch and token are set in Admin → Configuration Parameters → WebAPI; everything is read-only, so even a leaked token cannot cause writes.
📍 Endpoints
| Method | Path | Description |
|---|---|---|
| GET | /api/v1/list?type=news&num=10&page=1&site=1&token=xxx |
Content list |
| GET | /api/v1/detail?type=news&id=13&site=1&token=xxx |
Content detail (with body) |
| GET | /api/v1/categories?site=1&token=xxx |
Category list |
# List
GET /api/v1/list?type=news&num=10&page=1&site=1&token=xxx
# type: news(posts) / products / cases / jobs / pages
# num: 1-100, default 10; page: default 1; site: defaults to the current default site
# Returns:
{ "ok": true, "type": "news", "total": 212, "page": 1, "num": 10,
"items": [ { "id":13, "slug":"", "title":"...", "summary":"...",
"image":"...", "url":"/news/13", "seo_title":"", "keywords":"",
"description":"", "created_at":"2026-08-03T..." } ] }
# Detail
GET /api/v1/detail?type=news&id=13&token=xxx
# Returns {"ok":true,"item":{ ...same fields as above + "content":"body HTML" }}
# Categories
GET /api/v1/categories?token=xxx
# Returns {"ok":true,"total":8,"items":[{ "id":2,"name":"Product","link":"products",
# "url":"/category/products","description":"" }]}
Field notes: url is assembled per the admin “URL Rules” (including site prefix and suffix, e.g. /en/news/13.html) and can be used by the front end directly; the jobs table has no slug column, so its slug is always empty and its URL always uses the ID; title for products comes from the name column.
🔐 Auth and interception (managed uniformly by the APIAuth middleware, order: switch → IP whitelist → token → rate limit):
· Switch: when webapi_enabled≠1, all requests return 404 {"ok":false,"error":"API not enabled"}.
· IP whitelist: when webapi_allow_ip is non-empty, non-whitelisted IPs get 403 (supports single IPs and CIDR, comma / newline separated).
· Token: when webapi_token is non-empty, callers must supply it via the query parameter ?token= or the header X-API-Token; errors return 401; an empty token means no validation (not recommended). Click “Generate Token” on the config page, which calls GET /admin/config/api-token to obtain a 32-character random string.
· Rate limit: webapi_limit is the per-IP per-minute cap (default 60); exceeding it returns 429.
Write operations such as manual push / token generation go through admin session auth (administrator login) and are not exposed externally.
🔍 Search Engine Proactive Push (Baidu API / IndexNow)
Configured in the “Baidu API” and “IndexNow Push” tabs of Admin → Configuration Parameters, it proactively submits site links to search engines to speed up indexing. Prerequisite: the domain is already filled in under Site Info (otherwise absolute URLs cannot be assembled).
📍 Configuration Items
| Source | Settings | Description |
|---|---|---|
| Baidu API | baidu_enabled / baidu_site / baidu_token / baidu_auto_push |
Site (domain), admission key (obtained from the Baidu Webmaster platform); once enabled, pushes to data.zz.baidu.com/urls |
| IndexNow Push | indexnow_enabled / indexnow_key / indexnow_endpoint / indexnow_key_location / indexnow_auto_push |
API Key (obtained from Bing Webmaster; the key file is a .txt placed at the site root); default endpoint api.indexnow.org/IndexNow (one submission reaches Bing / Yandex / Seznam / Naver) |
- Manual push: click “Push Now” on the config page, calling
POST /admin/config/push(formtarget=baidu|indexnow,limit=200). Submission scope = home page + three main list pages + category pages + recent details (200 by default). Returns{ok,msg,count}. - Auto push after save: once the corresponding
_auto_pushis enabled, every content save / publish asynchronously submits that URL; failures are only logged and never block the content-save main flow.
Return code meanings: Baidu HTTP 200 & error=0 means success; IndexNow 200 received, 202 queued (also returned when the Key is unverified), 429 rate-limited.
🛡️ Security Configuration
Set admin and upload security policies uniformly in Admin → Configuration Parameters → Security Configuration; leaving everything at defaults preserves historical behavior (unrestricted).
📍 Settings
| Setting | Description | Default |
|---|---|---|
sec_login_fail_limit |
Lock the account after this many consecutive login failures (0 = unrestricted) | 5 |
sec_login_lock_minutes |
Lock duration after the threshold is triggered (minutes) | 15 |
sec_idle_timeout |
Admin idle timeout (minutes); re-login required after timeout | 30 |
sec_session_ip_bind |
Session IP binding: the session becomes invalid when the client IP changes after login (prevents session hijacking) | Enabled |
sec_admin_ip_whitelist |
Admin access IP whitelist (single IPs / CIDR, comma or newline separated); wired into the auth middleware — when non-empty, non-whitelisted IPs cannot enter the admin | Unrestricted |
sec_upload_ext_blacklist |
Upload extension blacklist (no dots, lowercase); matches are rejected | Unrestricted |
Reads are centralized in internal/handlers/security.go, called uniformly by the middleware package (auth, login rate limiting) and the WebAPI; the admin IP whitelist and the WebAPI’s webapi_allow_ip are two independent configurations guarding the admin and the external API respectively.
🛠️ System Update (System Info and Maintenance)
A new operations page (Admin → System Settings → System Update, /admin/system-update) showing runtime info and common maintenance operations.
📍 Displayed Info
| Item | Description |
|---|---|
| Program version / build time | version / buildTime injected at compile time |
| Go version | Runtime runtime.Version() |
| Database size | Size of the cms.db file |
| Uptime | Since process start |
| Static site size | Size of the static export directory |
📍 Maintenance Operations (POST, administrator login required)
| Operation | API | Description |
|---|---|---|
| Clear runtime logs | POST /system/clear-logs |
Empties log files under logs/ |
| Optimize database | POST /system/optimize-db |
Runs VACUUM on SQLite to reclaim space and optimize indexes |
[← Image Upload Rules](20-upload.html) [License and Email Services →](22-license.html)
CloudSite SaaS