zkrebbekx/go-mermaid

Render Mermaid diagrams to SVG in pure Go — no headless browser, no Node.

Go

6

99 commits

updated Oct 17, 2026

See the code

README

go-mermaid

CI codecov Go Reference Go Report Card License: MIT

Render Mermaid diagrams to SVG in pure Go — no headless browser, no Node.js, no JavaScript runtime. Just a library and a single static binary.

Status: pre-1.0, actively developed. 20 diagram types supported (see the table below). Not affiliated with the Mermaid project; this is an independent, compatible renderer.

Rendered by go-mermaid (PNG at 2x) from the fixtures in testdata/golden. Regenerate them after any rendering change with go run ./internal/gallery/cmd. CI checks that each image still matches the diagram it came from.

FlowchartSequenceClass
flowchartsequenceclass
StateERPie
stateerpie
GanttGit graphMindmap
ganttgitgraphmindmap

Why

Every existing Go path to Mermaid SVG shells out to headless Chrome or a Node sidecar. That's heavy, slow, and hard to deploy. go-mermaid does the parse → layout → SVG pipeline natively, so you can render diagrams inside any Go service or CLI with zero external dependencies.

Install

Library:

go get github.com/zkrebbekx/go-mermaid

CLI:

go install github.com/zkrebbekx/go-mermaid/cmd/mermaid@latest

Homebrew:

brew install zkrebbekx/tap/mermaid

Docker:

echo "graph LR; A-->B" | docker run -i --rm ghcr.io/zkrebbekx/go-mermaid > out.svg

Prebuilt binaries for Linux/macOS/Windows (amd64/arm64) are attached to each GitHub release.

Usage

Library

package main

import (
	"os"

	mermaid "github.com/zkrebbekx/go-mermaid"
)

func main() {
	svg, err := mermaid.Render("graph TD\n  A[Start] --> B{OK?}\n  B -->|yes| C([Done])")
	if err != nil {
		panic(err)
	}
	os.WriteFile("diagram.svg", svg, 0o644)
}

With options:

svg, err := mermaid.Render(src,
	mermaid.WithTheme(mermaid.Dark),
	mermaid.WithFont("Inter", 14),
	mermaid.WithPadding(24),
	mermaid.WithSpacing(50, 60),
)

CLI

mermaid diagram.mmd > diagram.svg
echo "graph LR; A-->B-->C" | mermaid -theme dark -o out.svg
mermaid a.mmd b.mmd c.mmd      # batch: writes a.svg, b.svg, c.svg
mermaid -list-types            # list supported diagram types
mermaid -list-themes           # list themes
mermaid serve -addr :8080      # HTTP endpoint (POST source / GET ?src=, ?format=png)
mermaid -png -scale 2 -o d.png d.mmd   # PNG output (rasterized)

PNG output

The core library is dependency-free and emits SVG. PNG rasterization lives in a separate package so only PNG users pull the rasterizer dependency:

import "github.com/zkrebbekx/go-mermaid/raster"

img, err := raster.PNG("graph TD\n A --> B", 2) // 2 = scale factor

PNG is also available from the CLI (-png -scale N) and the HTTP server (?format=png&scale=N). Output formats: SVG (core) and PNG (raster).

Error handling

Render wraps stage-specific sentinels so you can branch on the failure, and parse errors carry source position:

svg, err := mermaid.Render(src)
if errors.Is(err, mermaid.ErrParse) {
	var pe *mermaid.ParseError
	if errors.As(err, &pe) {
		log.Printf("syntax error at line %d col %d: %s", pe.Line, pe.Col, pe.Msg)
	}
}

Sentinels: ErrParse, ErrLayout, ErrRender, ErrUnsupported.

Diagram types

The renderer dispatches on the diagram header. Status vs. Mermaid:

TypeHeaderNotes
Flowchartgraph / flowchart12 shapes, subgraphs, styling, orthogonal edges
SequencesequenceDiagramnotes, activations, loop/alt/opt frames, autonumber
ClassclassDiagrammembers, 6 relationship types
StatestateDiagram-v2start/end, composite states
Entity-relationshiperDiagramattributes, crow's-foot cardinality
Piepielegend with percentages
User journeyjourneyscored tasks, section bands
QuadrantquadrantChartaxes, 4 quadrants, points
Git graphgitGraphbranches, merges, tags
Timelinetimelinesections, periods, events
Mindmapmindmapindentation hierarchy
Ganttganttdates, durations, after deps
C4C4Context / C4Containerpeople, systems, relationships
RequirementrequirementDiagramrequirements, elements, typed relations
Sankeysankey-betaproportional flow bands
XY chartxychart-betabar and line charts
Blockblock-betacolumn grid of labeled blocks
Kanbankanbancolumns of cards by indentation
Packetpacket-betabit/byte field table
Radarradar-betapolar chart with data curves

Flowchart extras: curved edges (WithCurvedEdges), clickable nodes (click ID href).

Unsupported types return ErrUnsupported. A ---/title: front-matter block and accTitle:/accDescr: (SVG <title>/<desc>) are honored for all types. Themes: default, dark, neutral, forest, base, plus custom palettes (WithCustomTheme). Background is configurable (WithBackground, WithTransparentBackground).

Rendering is fast — roughly 10–50µs per diagram with no external processes.

Flowchart syntax

FeatureExample
Directionsgraph TD, TB, BT, LR, RL
RectangleA[Label]
RoundedA(Label)
StadiumA([Label])
CircleA((Label))
DiamondA{Label}
HexagonA{{Label}}
SubroutineA[[Label]]
CylinderA[(Label)]
ParallelogramA[/Label/], A[\Label\]
TrapezoidA[/Label\], A[\Label/]
Arrow / open / dotted / thickA --> B, A --- B, A -.-> B, A ==> B
Edge labelA -->|text| B, A -- text --> B
Subgraphsubgraph T … end
StylingclassDef, class, style, A:::cls
Linkclick A href "url"
Separators / commentsA-->B; B-->C, %% comment

Sequence syntax

FeatureExample
Participantparticipant A / actor A
Aliasparticipant A as Alice
Message + arrowheadA->>B: text
Reply (dashed)B-->>A: text
Plain lineA->B / A-->B
Cross endA-xB / A--xB
Self-messageA->>A: text
NoteNote right of A: text, Note over A,B: text
ActivationA->>+B: ..., B-->>-A: ..., activate/deactivate
Framesloop/alt/opt/par … end, autonumber

Roadmap

Done

  • 20 diagram types (see table above)
  • Sugiyama flowchart layout: crossing minimization, dummy-node bends, barycenter positioning, orthogonal + curved edges
  • Flowchart: 12 shapes, subgraphs, classDef/style/:::, clickable nodes
  • Sequence: notes, activations, loop/alt/opt frames, autonumber
  • Front-matter titles, accessibility (role/title/desc/accTitle), 5 themes, configurable/transparent background
  • SVG + PNG output (PNG via the raster subpackage)
  • CLI (stdin/file/batch, serve HTTP, -list-*), Render/RenderTo API
  • goconvey BDD tests, golden SVGs, fuzz-tested parsers, ~92% coverage
  • README examples gallery (sample PNG per diagram type), regenerated by ./internal/gallery/cmd and drift-checked in CI
  • Font-metric-aware label sizing (Helvetica advance widths)
  • Custom theme registration (WithCustomTheme)
  • Distribution: prebuilt binaries, Homebrew cask, ghcr.io Docker image

Later

  • Network-simplex ranking (tighter flowchart layouts)
  • Spline edge routing
  • Richer fidelity: class generics/annotations, sequence create/destroy/ highlight, ER attribute keys
  • More diagram types (architecture-beta, treemap, zenuml)
  • Toward v1.0: freeze the public API

Architecture

Each diagram type has a self-contained pipeline; the public Render dispatches on the header. The flowchart pipeline is:

source → lexer → parser → domain.Graph → layout → render → SVG

internal/domain holds the flowchart model; internal/sequence is the self-contained sequence pipeline; internal/theme and internal/svgutil are shared by all renderers. See CONTRIBUTING.md.

Releasing

Releases are automated with release-please + GoReleaser, driven by Conventional Commits. See RELEASING.md for the versioning policy and the optional AI code-review setup.

License

MIT © Zac Krebbekx

diagrams
flowchart
go
golang
mermaid
no-dependencies
renderer
svg

zkrebbekx/go-mermaid

Render Mermaid diagrams to SVG in pure Go — no headless browser, no Node.

Go

6

99 commits

updated Oct 17, 2026

See the code

README

go-mermaid

CI codecov Go Reference Go Report Card License: MIT

Render Mermaid diagrams to SVG in pure Go — no headless browser, no Node.js, no JavaScript runtime. Just a library and a single static binary.

Status: pre-1.0, actively developed. 20 diagram types supported (see the table below). Not affiliated with the Mermaid project; this is an independent, compatible renderer.

Rendered by go-mermaid (PNG at 2x) from the fixtures in testdata/golden. Regenerate them after any rendering change with go run ./internal/gallery/cmd. CI checks that each image still matches the diagram it came from.

FlowchartSequenceClass
flowchartsequenceclass
StateERPie
stateerpie
GanttGit graphMindmap
ganttgitgraphmindmap

Why

Every existing Go path to Mermaid SVG shells out to headless Chrome or a Node sidecar. That's heavy, slow, and hard to deploy. go-mermaid does the parse → layout → SVG pipeline natively, so you can render diagrams inside any Go service or CLI with zero external dependencies.

Install

Library:

go get github.com/zkrebbekx/go-mermaid

CLI:

go install github.com/zkrebbekx/go-mermaid/cmd/mermaid@latest

Homebrew:

brew install zkrebbekx/tap/mermaid

Docker:

echo "graph LR; A-->B" | docker run -i --rm ghcr.io/zkrebbekx/go-mermaid > out.svg

Prebuilt binaries for Linux/macOS/Windows (amd64/arm64) are attached to each GitHub release.

Usage

Library

package main

import (
	"os"

	mermaid "github.com/zkrebbekx/go-mermaid"
)

func main() {
	svg, err := mermaid.Render("graph TD\n  A[Start] --> B{OK?}\n  B -->|yes| C([Done])")
	if err != nil {
		panic(err)
	}
	os.WriteFile("diagram.svg", svg, 0o644)
}

With options:

svg, err := mermaid.Render(src,
	mermaid.WithTheme(mermaid.Dark),
	mermaid.WithFont("Inter", 14),
	mermaid.WithPadding(24),
	mermaid.WithSpacing(50, 60),
)

CLI

mermaid diagram.mmd > diagram.svg
echo "graph LR; A-->B-->C" | mermaid -theme dark -o out.svg
mermaid a.mmd b.mmd c.mmd      # batch: writes a.svg, b.svg, c.svg
mermaid -list-types            # list supported diagram types
mermaid -list-themes           # list themes
mermaid serve -addr :8080      # HTTP endpoint (POST source / GET ?src=, ?format=png)
mermaid -png -scale 2 -o d.png d.mmd   # PNG output (rasterized)

PNG output

The core library is dependency-free and emits SVG. PNG rasterization lives in a separate package so only PNG users pull the rasterizer dependency:

import "github.com/zkrebbekx/go-mermaid/raster"

img, err := raster.PNG("graph TD\n A --> B", 2) // 2 = scale factor

PNG is also available from the CLI (-png -scale N) and the HTTP server (?format=png&scale=N). Output formats: SVG (core) and PNG (raster).

Error handling

Render wraps stage-specific sentinels so you can branch on the failure, and parse errors carry source position:

svg, err := mermaid.Render(src)
if errors.Is(err, mermaid.ErrParse) {
	var pe *mermaid.ParseError
	if errors.As(err, &pe) {
		log.Printf("syntax error at line %d col %d: %s", pe.Line, pe.Col, pe.Msg)
	}
}

Sentinels: ErrParse, ErrLayout, ErrRender, ErrUnsupported.

Diagram types

The renderer dispatches on the diagram header. Status vs. Mermaid:

TypeHeaderNotes
Flowchartgraph / flowchart12 shapes, subgraphs, styling, orthogonal edges
SequencesequenceDiagramnotes, activations, loop/alt/opt frames, autonumber
ClassclassDiagrammembers, 6 relationship types
StatestateDiagram-v2start/end, composite states
Entity-relationshiperDiagramattributes, crow's-foot cardinality
Piepielegend with percentages
User journeyjourneyscored tasks, section bands
QuadrantquadrantChartaxes, 4 quadrants, points
Git graphgitGraphbranches, merges, tags
Timelinetimelinesections, periods, events
Mindmapmindmapindentation hierarchy
Ganttganttdates, durations, after deps
C4C4Context / C4Containerpeople, systems, relationships
RequirementrequirementDiagramrequirements, elements, typed relations
Sankeysankey-betaproportional flow bands
XY chartxychart-betabar and line charts
Blockblock-betacolumn grid of labeled blocks
Kanbankanbancolumns of cards by indentation
Packetpacket-betabit/byte field table
Radarradar-betapolar chart with data curves

Flowchart extras: curved edges (WithCurvedEdges), clickable nodes (click ID href).

Unsupported types return ErrUnsupported. A ---/title: front-matter block and accTitle:/accDescr: (SVG <title>/<desc>) are honored for all types. Themes: default, dark, neutral, forest, base, plus custom palettes (WithCustomTheme). Background is configurable (WithBackground, WithTransparentBackground).

Rendering is fast — roughly 10–50µs per diagram with no external processes.

Flowchart syntax

FeatureExample
Directionsgraph TD, TB, BT, LR, RL
RectangleA[Label]
RoundedA(Label)
StadiumA([Label])
CircleA((Label))
DiamondA{Label}
HexagonA{{Label}}
SubroutineA[[Label]]
CylinderA[(Label)]
ParallelogramA[/Label/], A[\Label\]
TrapezoidA[/Label\], A[\Label/]
Arrow / open / dotted / thickA --> B, A --- B, A -.-> B, A ==> B
Edge labelA -->|text| B, A -- text --> B
Subgraphsubgraph T … end
StylingclassDef, class, style, A:::cls
Linkclick A href "url"
Separators / commentsA-->B; B-->C, %% comment

Sequence syntax

FeatureExample
Participantparticipant A / actor A
Aliasparticipant A as Alice
Message + arrowheadA->>B: text
Reply (dashed)B-->>A: text
Plain lineA->B / A-->B
Cross endA-xB / A--xB
Self-messageA->>A: text
NoteNote right of A: text, Note over A,B: text
ActivationA->>+B: ..., B-->>-A: ..., activate/deactivate
Framesloop/alt/opt/par … end, autonumber

Roadmap

Done

  • 20 diagram types (see table above)
  • Sugiyama flowchart layout: crossing minimization, dummy-node bends, barycenter positioning, orthogonal + curved edges
  • Flowchart: 12 shapes, subgraphs, classDef/style/:::, clickable nodes
  • Sequence: notes, activations, loop/alt/opt frames, autonumber
  • Front-matter titles, accessibility (role/title/desc/accTitle), 5 themes, configurable/transparent background
  • SVG + PNG output (PNG via the raster subpackage)
  • CLI (stdin/file/batch, serve HTTP, -list-*), Render/RenderTo API
  • goconvey BDD tests, golden SVGs, fuzz-tested parsers, ~92% coverage
  • README examples gallery (sample PNG per diagram type), regenerated by ./internal/gallery/cmd and drift-checked in CI
  • Font-metric-aware label sizing (Helvetica advance widths)
  • Custom theme registration (WithCustomTheme)
  • Distribution: prebuilt binaries, Homebrew cask, ghcr.io Docker image

Later

  • Network-simplex ranking (tighter flowchart layouts)
  • Spline edge routing
  • Richer fidelity: class generics/annotations, sequence create/destroy/ highlight, ER attribute keys
  • More diagram types (architecture-beta, treemap, zenuml)
  • Toward v1.0: freeze the public API

Architecture

Each diagram type has a self-contained pipeline; the public Render dispatches on the header. The flowchart pipeline is:

source → lexer → parser → domain.Graph → layout → render → SVG

internal/domain holds the flowchart model; internal/sequence is the self-contained sequence pipeline; internal/theme and internal/svgutil are shared by all renderers. See CONTRIBUTING.md.

Releasing

Releases are automated with release-please + GoReleaser, driven by Conventional Commits. See RELEASING.md for the versioning policy and the optional AI code-review setup.

License

MIT © Zac Krebbekx

diagrams
flowchart
go
golang
mermaid
no-dependencies
renderer
svg

Project health

Latest release

v0.1.6 · Sep 10, 2026

Releases this year

7