htmlrender

module
v0.0.0-...-fcc6260 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: MIT

README

htmlrender

Render HTML and Markdown cards into images from Go. Use an embedded renderer, a shared HTTP service, or a lightweight HTTP client. Both Blitz and Chromium are available.

简体中文 · AlonaBot integration · Native build

Use case Entry point
Small server or several bots sharing a renderer sdk/client → a service you operate
Rendering inside a Go application htmlrender.New with the required backends
Shell commands and a persistent local service cmd/h2i
AlonaBot plugins calling a rendering service sdk/client with the plugin's endpoint and token

The main Go package is htmlrender, imported from github.com/AlonaBot/htmlrender/sdk/htmlrender. The module remains github.com/AlonaBot/htmlrender; the CLI executable is h2i.

Public extension packages live under sdk, CLI process management and native bindings under internal, and integration tests and their resources under tests. All Go packages share the root go.mod, including the AlonaBot integration tests. All public imports use github.com/AlonaBot/htmlrender/sdk/...; the repository root contains engineering and deployment files.

For a ready-to-run shared service, use the Docker and Compose guide. For repository work, read development, contributing and the Changelog.

Call a remote service

go get github.com/AlonaBot/htmlrender/sdk/htmlrender@main
import (
    "github.com/AlonaBot/htmlrender/sdk/htmlrender"
    "github.com/AlonaBot/htmlrender/sdk/client"
)

c, err := client.New(client.Config{
    Endpoint: "https://render.example.com",
    Token:    token,
})
if err != nil {
    return err
}
defer c.Close()

result, err := c.Render(ctx, htmlrender.Request{
    HTML: `<article id="card" style="width:600px;padding:24px"><h1>Hello, world</h1></article>`,
    Engine: htmlrender.Chromium,
    Options: htmlrender.Options{Width: 800, Selector: "#card"},
})
// result.Data contains the image bytes; result.Width/Height are physical pixels.

The client builds with CGO_ENABLED=0. Chrome and the Blitz native library run on the rendering host. Fonts, CSS and images travel with the request using Assets as shown below.

Render inside a Go application

import (
    "github.com/AlonaBot/htmlrender/sdk/htmlrender"
    "github.com/AlonaBot/htmlrender/sdk/backend/chromium"
)

renderer, err := htmlrender.New(htmlrender.Config{
    DefaultEngine: htmlrender.Chromium,
    Engines: map[string]htmlrender.EngineConfig{
        htmlrender.Chromium: {New: chromium.Factory(""), Concurrency: 2},
    },
})
if err != nil {
    return err
}
defer renderer.Close()

result, err := renderer.Render(ctx, htmlrender.Request{Markdown: "# A card from Go"})

Pass the same renderer to callers in the process. Chromium shares one browser across task slots and creates an independent browser context for each request. Blitz creates one native context per task slot. Engines initialize on first use; Warmup(engine) initializes one early. Close waits for admitted tasks and closes initialized backends.

To use Blitz, import github.com/AlonaBot/htmlrender/sdk/backend/blitz, register htmlrender.Blitz: {New: blitz.New}, and follow the native linking instructions. An empty default engine selects Blitz; an omitted request engine uses the configured default. Engine failures preserve their cause.

Send fonts and images with the card

assets, err := htmlrender.AssetsFromFS(os.DirFS("assets"))
if err != nil {
    return err
}
result, err := c.Render(ctx, htmlrender.Request{
    HTML: `<link rel="stylesheet" href="styles/card.css"><article id="card">Hello</article>`,
    Assets: assets,
    Engine: htmlrender.Chromium,
    Options: htmlrender.Options{Selector: "#card", OmitBackground: true},
})

Assets maps relative slash-separated paths to file bytes. AssetsFromFS also accepts embed.FS or an fs.Sub view. It rejects symlinks and special files. Nested CSS references such as ../fonts/Roboto.ttf retain their meaning. A request-local loopback server serves the bundle until rendering finishes; JSON transports byte slices as base64.

Choose either Assets or BaseURL. BaseURL keeps its existing meaning: relative resources load from that address on the rendering host. HTTP(S) resource URLs remain available. A file:// URL reads the rendering host's files. Resource fetch failures return the URL and cause to the caller. Blitz uses upstream decoding behavior, so invalid image bytes can produce a successful render with the image omitted; Chromium reports image decoding failures.

Render templates in the caller, then pass the generated HTML to Request.HTML. See custom HTML and templates for html/template, bundled assets and local/HTTP calls. HTML and Markdown are alternative inputs.

Build and use the CLI

The toolchain uses Go 1.27.3, Rust 1.91 or newer, and a C compiler. Install Chrome/Chromium on the rendering host. Linux additionally needs Fontconfig development files; install Chinese fonts for Chinese cards, for example libfontconfig1-dev and fonts-noto-cjk on Debian/Ubuntu.

asdf install
make build
./bin/h2i render tests/testdata/card/card.html \
    --assets-dir tests/testdata/card --selector '#card' \
    --engine blitz --transparent -o card.png
./bin/h2i render tests/testdata/card/card.html \
    --assets-dir tests/testdata/card --selector '#card' \
    --engine chromium --endpoint https://render.example.com -o remote.png

render runs in the CLI process by default and exits after writing the image. Use --endpoint to call an HTTP service; supply its credentials through HTMLRENDER_TOKEN or --token. Start a persistent service explicitly with start or serve, then pass its address through --endpoint when rendering.

./bin/h2i start --concurrency 2
./bin/h2i status
./bin/h2i stop

Persistent services share an instance for one system user and runtime directory. Startup settings stay effective until stopped. The default directory is the system user cache directory's t2i-go/default; service.log lives there. start/status/stop use a private Unix control socket on macOS/Linux. stop waits for active tasks.

Other render flags include --width, --height, --dpr, --clip x,y,width,height, --full-page=false, --format jpeg, --quality, --base-url, and --resource-timeout-ms. Selectors capture the first matching element and are mutually exclusive with Clip. Without a selector, full-page output retains at least the viewport height (800×720 by default). DPR scales the output pixels. PNG supports transparency; JPEG composites onto white.

Deploy a shared service

set -x HTMLRENDER_TOKEN 'a-secret-you-manage'
./bin/h2i serve --listen 127.0.0.1:8999 \
    --runtime-dir /var/lib/htmlrender/runtime \
    --data-dir /var/lib/htmlrender/images

Place an HTTPS reverse proxy in front of the loopback listener, or expose it on a private network. Configure clients with that URL and token. An empty token enables unauthenticated operation for the existing local workflow.

Run the renderer as a dedicated user in an isolated container or VM, with only the required fonts and data mounted and with network access controlled for your deployment. Accepted HTML can run scripts in Chromium and load resources accessible to the rendering account. Give endpoint credentials to trusted callers.

HTTP route Behavior
POST /v1/render JSON request → image bytes plus X-Image-Width, X-Image-Height, X-Render-Engine, X-Render-Duration
POST /text2img/generate AstrBot-style input; image bytes, or a stored reference with json=true
GET /text2img/data/<id>.png Read a stored image; also supports .jpeg
GET /healthz Engine/runtime status; token omitted

With a configured token, rendering and stored-image reads require Authorization: Bearer <token>. The health endpoint remains public. AstrBot references retain {"code":0,"message":"success","data":{"id":"data/<id>.png"}}; images remain until explicitly cleaned. Errors retain their complete message.

When embedding the HTTP handler, httpapi.Config.DataDir is optional for image responses. AstrBot json=true requires it and creates the directory on first use.

Queued requests respond to context cancellation. Chromium cancels the request's browser context. An in-progress Blitz native call completes before its slot is released and cancellation is reported. Closing a client releases its idle connections and leaves the service running.

Local resource sample

Measured on 2026-11-29, macOS arm64, release build, a 640×460 card at DPR 1 over loopback HTTP. Startup includes engine warmup; warm rendering is the wall-clock median of the next five requests. RSS is the idle service and all child processes after those renders.

Engine Startup (ms) First HTTP render (ms) Warm HTTP median (ms) Idle tree RSS (MiB)
blitz 1736.1 73.2 26.8 55.2
chromium 587.2 266.9 183.9 873.1

Verify the implementation

make test
make integration

make integration exercises local/HTTP × Blitz/Chromium with real resources and race detection, then runs real Core, a profile-card plugin using the HTTP client directly and the test Adapter, including an image exceeding 1 MiB. It requires Chrome. CI runs these checks on Linux amd64 and uploads the rendered PNGs. macOS arm64 is the local development platform.

Project code uses MIT. The native bridge and test font retain their source licenses; see third-party notices.

Directories

Path Synopsis
alonabot module
cmd
h2i command
h2i 命令装配渲染库、HTTP 服务与本机实例控制。
h2i 命令装配渲染库、HTTP 服务与本机实例控制。
internal
blitznative
Package blitznative 是 xo/blitz v0.5.0 C ABI 绑定的精简版本。
Package blitznative 是 xo/blitz v0.5.0 C ABI 绑定的精简版本。
local
Package local 管理同一用户、同一运行目录下的长期驻留服务。
Package local 管理同一用户、同一运行目录下的长期驻留服务。
scripts
check command
check 命令检查 htmlrender 的源码边界、文档注释和本地文档引用。
check 命令检查 htmlrender 的源码边界、文档注释和本地文档引用。
sdk
backend/blitz
Package blitz 通过本仓的 HTML/RGBA 桥接提供 CPU 渲染后端。
Package blitz 通过本仓的 HTML/RGBA 桥接提供 CPU 渲染后端。
backend/chromium
Package chromium 通过 CDP 管理共享浏览器及每次渲染的独立上下文。
Package chromium 通过 CDP 管理共享浏览器及每次渲染的独立上下文。
client
Package client 提供无需 CGO 的 htmlrender HTTP 客户端。
Package client 提供无需 CGO 的 htmlrender HTTP 客户端。
htmlrender
Package htmlrender 提供 HTML 文档的共享渲染生命周期与图片输出。
Package htmlrender 提供 HTML 文档的共享渲染生命周期与图片输出。
httpapi
Package httpapi 将共享 Renderer 暴露为通用与 AstrBot 风格的 HTTP 接口。
Package httpapi 将共享 Renderer 暴露为通用与 AstrBot 风格的 HTTP 接口。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL