htmlrender

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

English · 简体中文

htmlrender

CI MIT Go 1.27.3 Release Go Reference

Render HTML and Markdown cards into images from Go.
Embed the renderer, run a shared HTTP service, or call one with a lightweight client.

Templates · AlonaBot integration · Deployment · Native build · Changelog · Contributing · Report an issue

Features

  • Two engines: Blitz renders static HTML/CSS on the CPU with a small memory footprint; Chromium runs a full browser with JavaScript. Choose per request.
  • Three ways to call: render in process with htmlrender.New, serve POST /v1/render from h2i serve or Docker Compose, or call a service through client, which builds with CGO_ENABLED=0.
  • Self-contained cards: send fonts, CSS and images with the request as Assets; relative paths keep their meaning.
  • Precise output: capture an element by selector or a clip rectangle, choose viewport-only or full-page output, scale by DPR, and write PNG with transparency or JPEG.
  • Shared rendering: per-engine concurrency, lazy initialization, health checks and Chromium recovery let several bots share one renderer.

Choose an entry point

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

The main Go package htmlrender is the module root, github.com/AlonaBot/htmlrender; the CLI executable is h2i.

Public packages are the root package, client, server, engine/blitz and engine/chromium. CLI process management and native bindings live under internal, and integration tests and their resources under tests. All Go packages share the root go.mod.

Call a remote service

go get github.com/AlonaBot/htmlrender@latest
import (
    "github.com/AlonaBot/htmlrender"
    "github.com/AlonaBot/htmlrender/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{ViewportWidth: 800, Selector: "#card"},
})
// result.ImageBytes 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"
    "github.com/AlonaBot/htmlrender/engine/chromium"
)

renderer, err := htmlrender.New(htmlrender.Config{
    DefaultEngine: htmlrender.Chromium,
    Engines: map[htmlrender.EngineName]htmlrender.EngineConfig{
        htmlrender.Chromium: {New: chromium.New(""), 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. Concurrency sets how many renders an engine runs in parallel. Chromium shares one browser across them and creates an independent browser context for each request; Blitz creates one native context for each. Engines initialize on first use; Warmup(engine) initializes one early. Close waits for admitted tasks and closes initialized engines.

To use Blitz, import github.com/AlonaBot/htmlrender/engine/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", Transparent: 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

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-Render-Width, X-Render-Height, X-Render-Engine, X-Render-Duration
GET /healthz Engine/runtime status; token omitted

The request body is the JSON form of htmlrender.Request; option fields use the Go field names in snake case, such as viewport_width, viewport_only, format, jpeg_quality and transparent, and resource_timeout_ms carries ResourceTimeout in whole milliseconds. Unknown fields are rejected.

With a configured token, rendering requires Authorization: Bearer <token>. The health endpoint remains public. Failures return {"error":"<complete message>"} with HTTP 400 for caller-correctable input and 500 otherwise.

Embed the HTTP API in another server with server.New(renderer, server.Config{Token: token}), which returns an http.Handler.

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

Resource usage

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

After fixing macOS native autorelease accumulation on 2026-11-30, 1100 consecutive Blitz HTTP renders of the same bundled card used 57.9 MiB RSS at request 100 and 60.2 MiB at request 1100, with four concurrent clients and engine concurrency 1. The sample includes bundled fonts, CSS and images.

Documentation and contributing

What you want to do Start here
Render custom HTML or Go templates Custom HTML and templates
Call a renderer from an AlonaBot plugin AlonaBot integration
Run a shared service with Docker Docker and Compose
Build and link the Blitz native library Native build
Change the code or run checks Development · Architecture · Coding standards
Report a problem or submit a change Contributing
See what changed between versions Changelog
make test
make integration

make integration exercises local/HTTP × Blitz/Chromium with real resources and race detection. It requires Chrome. CI runs these checks on Linux amd64 and uploads the rendered PNGs. macOS arm64 is the local development platform. Platform-specific plugin integration tests belong in the consuming plugin's repository.

License

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

Documentation

Overview

Package htmlrender 提供 HTML 文档的共享渲染生命周期与图片输出。

Request 携带 HTML、Markdown 和随包资源,Renderer 通过显式登记的 Engine 完成布局并返回 Result。AssetsFromFS 读取素材,MarkdownToHTML 生成静态 HTML。

Index

Constants

View Source
const (
	// Version 标识渲染库、CLI 与 HTTP 服务的产品版本。
	Version = "0.1.0"

	// Blitz 使用静态 HTML/CSS 的 CPU 渲染引擎。
	Blitz EngineName = "blitz"
	// Chromium 使用浏览器布局与 JavaScript。
	Chromium EngineName = "chromium"

	// PNG 指定 PNG 编码。
	PNG Format = "png"
	// JPEG 指定 JPEG 编码。
	JPEG Format = "jpeg"

	// EngineIdle 标识引擎尚未初始化。
	EngineIdle EngineState = "idle"
	// EngineStarting 标识引擎正在初始化。
	EngineStarting EngineState = "starting"
	// EngineReady 标识引擎已完成初始化。
	EngineReady EngineState = "ready"
	// EngineFailed 标识引擎初始化或运行失败。
	EngineFailed EngineState = "failed"

	// DefaultViewportWidth 指定省略宽度时的 CSS 像素数。
	DefaultViewportWidth = 800
	// DefaultViewportHeight 指定省略高度时的 CSS 像素数。
	DefaultViewportHeight = 720
	// DefaultJPEGQuality 指定省略 JPEG 质量时的编码质量。
	DefaultJPEGQuality = 90
	// DefaultResourceTimeout 指定省略资源期限时的加载期限。
	DefaultResourceTimeout = 10 * time.Second
)

Variables

View Source
var ErrClosed = errors.New("renderer is closed")

ErrClosed 标识 Renderer 已进入关闭过程。

Functions

func AssetsFromFS

func AssetsFromFS(files fs.FS) (map[string][]byte, error)

AssetsFromFS 读取可随请求传递的资源,路径相对于 files 的根目录。 可传入 embed.FS 的子目录;符号链接和特殊文件返回错误。

func MarkdownToHTML

func MarkdownToHTML(source string) (string, error)

MarkdownToHTML 生成两种引擎共用的静态文档,允许调用方提供内嵌 HTML。

Types

type Config

type Config struct {
	DefaultEngine EngineName
	Engines       map[EngineName]EngineConfig
}

Config 登记可用引擎;DefaultEngine 为空时使用 Blitz。

type Engine

type Engine interface {
	// Render 读取页面资源并返回所选页面区域的图像。
	Render(context.Context, Page) (image.Image, error)
	// Close 释放引擎拥有的资源。
	Close() error
}

Engine 返回整页、viewport 或 Selector 指定的图像;手动裁剪和编码由 Renderer 完成。 实现可额外提供 Err() error,供 Renderer.Status 读取运行期间的故障。

type EngineConfig

type EngineConfig struct {
	New         func() (Engine, error)
	Concurrency int
}

EngineConfig 配置引擎构造函数及并发数;Concurrency 为零时为 1。

type EngineName

type EngineName string

EngineName 标识调用方选择、Renderer 登记的渲染引擎。

type EngineState

type EngineState string

EngineState 标识引擎的初始化与运行状态。

type EngineStatus

type EngineStatus struct {
	State       EngineState `json:"state"`
	Concurrency int         `json:"concurrency"`
	Error       string      `json:"error,omitempty"`
}

EngineStatus 提供引擎状态及已初始化的并发数;初始化完成前 Concurrency 为零。

type Format

type Format string

Format 标识输出图片的编码。

func (Format) MediaType

func (f Format) MediaType() string

MediaType 返回编码对应的 HTTP 媒体类型;未知编码返回空字符串。

type InputError

type InputError struct {
	Cause error // 构造时提供实际错误;通过 Unwrap 保留原始错误类型。
}

InputError 保留调用方可以修正的输入错误及其原因链。

func (*InputError) Error

func (e *InputError) Error() string

Error 返回输入校验的完整原因。

func (*InputError) Unwrap

func (e *InputError) Unwrap() error

Unwrap 返回输入校验失败的原始原因。

type Options

type Options struct {
	ViewportWidth     int     `json:"viewport_width,omitempty"`
	ViewportHeight    int     `json:"viewport_height,omitempty"`
	DeviceScaleFactor float64 `json:"device_scale_factor,omitempty"`
	ViewportOnly      bool    `json:"viewport_only,omitempty"`
	Clip              *Rect   `json:"clip,omitempty"`
	Selector          string  `json:"selector,omitempty"` // 第一个匹配元素的边界,与 Clip 互斥。
	Format            Format  `json:"format,omitempty"`
	JPEGQuality       int     `json:"jpeg_quality,omitempty"`
	Transparent       bool    `json:"transparent,omitempty"`
	// ResourceTimeout 必须为整毫秒;JSON 以 resource_timeout_ms 毫秒整数传递。
	ResourceTimeout time.Duration `json:"-"`
}

Options 指定 CSS 像素尺寸、截图区域与编码;DeviceScaleFactor 决定输出像素数。 ViewportOnly 为 false 时整页输出,true 时输出固定 viewport。

func (Options) MarshalJSON

func (o Options) MarshalJSON() ([]byte, error)

MarshalJSON 将 ResourceTimeout 编码为毫秒整数。

func (*Options) UnmarshalJSON

func (o *Options) UnmarshalJSON(data []byte) error

UnmarshalJSON 拒绝未知字段,并将 resource_timeout_ms 还原为 ResourceTimeout。

type Page

type Page struct {
	HTML    string
	BaseURL string
	Options Options
}

Page 携带已完成 Markdown 转换、默认值补齐和输入校验的引擎输入。

type Rect

type Rect struct {
	X      float64 `json:"x"`
	Y      float64 `json:"y"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

Rect 以 CSS 像素指定文档中的矩形。

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer 可被多个 goroutine 共享。Close 等待已进入的任务释放资源。

func New

func New(config Config) (*Renderer, error)

New 创建延迟初始化引擎的 Renderer,由宿主共享并在退出时关闭。

func (*Renderer) Close

func (r *Renderer) Close() error

Close 等待已进入的任务结束,关闭所有已初始化的引擎实例。

func (*Renderer) Render

func (r *Renderer) Render(ctx context.Context, request Request) (result Result, returnErr error)

Render 排队取得空闲引擎实例,完成资源加载、渲染和编码后释放本次资源。

func (*Renderer) Status

func (r *Renderer) Status() map[EngineName]EngineStatus

Status 返回独立的引擎状态快照,并读取引擎可选的 Err 方法反映运行故障。

func (*Renderer) Warmup

func (r *Renderer) Warmup(name EngineName) error

Warmup 提前初始化指定引擎;name 为空时使用配置的默认引擎。

type Request

type Request struct {
	HTML     string            `json:"html,omitempty"`
	Markdown string            `json:"markdown,omitempty"`
	BaseURL  string            `json:"base_url,omitempty"`
	Assets   map[string][]byte `json:"assets,omitempty"` // 相对路径到文件内容;与 BaseURL 互斥。
	Engine   EngineName        `json:"engine,omitempty"`
	Options  Options           `json:"options,omitempty"`
}

Request 选择 HTML 或 Markdown,并携带跨机可用的资源和渲染选项。

type Result

type Result struct {
	ImageBytes []byte
	MediaType  string
	Width      int
	Height     int
	Engine     EngineName
	Duration   time.Duration
}

Result 持有调用方所有的图片字节、物理像素尺寸和实际使用的引擎。

Directories

Path Synopsis
alonabot module
Package client 提供无需 CGO 的 htmlrender HTTP 客户端。
Package client 提供无需 CGO 的 htmlrender HTTP 客户端。
cmd
h2i command
h2i 命令装配渲染库、HTTP 服务与本机实例控制。
h2i 命令装配渲染库、HTTP 服务与本机实例控制。
engine
blitz
Package blitz 通过本仓的 HTML/RGBA 桥接提供 CPU 渲染引擎。
Package blitz 通过本仓的 HTML/RGBA 桥接提供 CPU 渲染引擎。
chromium
Package chromium 通过 CDP 管理共享浏览器及每次渲染的独立上下文。
Package chromium 通过 CDP 管理共享浏览器及每次渲染的独立上下文。
internal
blitznative
Package blitznative 绑定 Blitz C ABI,管理原生 Context、RGBA 内存和线程本地错误。
Package blitznative 绑定 Blitz C ABI,管理原生 Context、RGBA 内存和线程本地错误。
local
Package local 管理同一用户、同一运行目录下的长期驻留服务。
Package local 管理同一用户、同一运行目录下的长期驻留服务。
renderhttp
Package renderhttp 定义客户端、HTTP 服务和本机控制共同使用的渲染协议路径与元数据头。
Package renderhttp 定义客户端、HTTP 服务和本机控制共同使用的渲染协议路径与元数据头。
Package server 将共享 Renderer 暴露为 HTTP 渲染与健康检查接口。
Package server 将共享 Renderer 暴露为 HTTP 渲染与健康检查接口。

Jump to

Keyboard shortcuts

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