Markdown to HTML Converter — Go source
Render Markdown into clean, escaped HTML: headings, lists, links, images, code blocks and quotes. Every input is escaped first, so the output is always safe markup. Runs locally with a shareable link.
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package markdowntohtml is the Go twin of CosmoDev's src/lib/markdown-to-html.ts
// (dual source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics, never fails. The table-driven tests in
// markdown-to-html_test.go share vectors with src/lib/markdown-to-html.test.ts
// so the two implementations are held to the same contract.
//
// Hand-rolled CommonMark SUBSET — stdlib only, no dependencies, everything
// escaped before inline rules (raw HTML never passes through; security first).
// Supported blocks: ATX headings (all 6 levels), hr (--- *** ___), fenced code
// with language class and escaped body, blockquotes with nested blocks inside,
// flat ul (- * +) and ol lists, paragraphs. Inline precedence mirrors the TS
// exactly: code spans first (placeholder-protected and HTML-escaped), then
// images, links, bold, italic, strikethrough on escaped text. Soft line breaks
// inside a paragraph join with a newline; CRLF input is normalized. Empty or
// whitespace-only input is NOT an error. Not supported (by design, documented):
// raw HTML, tables, setext headings, nested lists, footnotes, autolinks.
package markdowntohtml
import (
"regexp"
"strconv"
"strings"
)
// htmlEscaper escapes &, <, > and " in that order, in a single pass.
// strings.NewReplacer never rescans its own output, which is exactly what the
// TS chained .replace calls achieve (escaping & first means the "&"
// entities introduced later are inert). Built once at package init instead of
// per escapeHtml call.
var htmlEscaper = strings.NewReplacer(
"&", "&",
"<", "<",
">", ">",
`"`, """,
)
// escapeHtml mirrors the TS escapeHtml: only & < > " are escaped, in that
// order.
func escapeHtml(s string) string {
return htmlEscaper.Replace(s)
}
var (
crlf = regexp.MustCompile(`\r\n?`) // \r\n or lone \r → \n
blockSplit = regexp.MustCompile(`\n{2,}`)
codeSpan = regexp.MustCompile("`([^`]+)`")
placeholder = regexp.MustCompile("\x00(\\d+)\x00")
headingRe = regexp.MustCompile(`^(#{1,6}) (.*)$`)
hrRe = regexp.MustCompile(`^(---+|\*\*\*+|___+)\s*$`)
ulRe = regexp.MustCompile(`^[-*+] `)
olRe = regexp.MustCompile(`^\d+\. `)
imageRe = regexp.MustCompile(`!\[([^\]]*)\]\(([^)\s]+)\)`)
linkRe = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)\)`)
boldStarRe = regexp.MustCompile(`\*\*([^*]+)\*\*`)
boldUndRe = regexp.MustCompile(`__([^_]+)__`)
italStarRe = regexp.MustCompile(`\*([^*]+)\*`)
italUndRe = regexp.MustCompile(`_([^_]+)_`)
strikeRe = regexp.MustCompile(`~~([^~]+)~~`)
)
// Result is the outcome of a rendering run, shaped like the sibling twins
// (JsonToSchema, MinifyCss). Error is "" (zero value) when there was no
// error; MarkdownToHtml never fails, so Error is always empty.
type Result struct {
Output string
Error string
}
// renderInline mirrors the TS inline pass: code spans first (placeholder-
// protected, HTML-escaped inside so no markdown or escaping inside backticks
// is reprocessed), then escapeHtml over the remaining text, then images,
// links, bold, italic, strikethrough — non-greedy pairs — and finally the
// code placeholders are restored.
func renderInline(s string) string {
var codes []string
idx := 0
text := codeSpan.ReplaceAllStringFunc(s, func(m string) string {
sub := codeSpan.FindStringSubmatch(m)
codes = append(codes, "<code>"+escapeHtml(sub[1])+"</code>")
p := "\x00" + strconv.Itoa(idx) + "\x00"
idx++
return p
})
text = escapeHtml(text)
text = imageRe.ReplaceAllString(text, `<img src="$2" alt="$1">`)
text = linkRe.ReplaceAllString(text, `<a href="$2">$1</a>`)
text = boldStarRe.ReplaceAllString(text, "<strong>$1</strong>")
text = boldUndRe.ReplaceAllString(text, "<strong>$1</strong>")
text = italStarRe.ReplaceAllString(text, "<em>$1</em>")
text = italUndRe.ReplaceAllString(text, "<em>$1</em>")
text = strikeRe.ReplaceAllString(text, "<del>$1</del>")
return placeholder.ReplaceAllStringFunc(text, func(m string) string {
n, err := strconv.Atoi(placeholder.FindStringSubmatch(m)[1])
if err != nil || n < 0 || n >= len(codes) {
return m // unreachable for internally generated placeholders
}
return codes[n]
})
}
// isBlockStart reports whether line begins one of the six supported
// non-paragraph blocks: ATX heading, hr, fenced code, blockquote, ul item or
// ol item. The paragraph gathering loop consumes lines until the first such
// line.
func isBlockStart(line string) bool {
return headingRe.FindStringSubmatch(line) != nil ||
hrRe.MatchString(line) ||
strings.HasPrefix(line, "```") ||
strings.HasPrefix(line, "> ") ||
ulRe.MatchString(line) ||
olRe.MatchString(line)
}
// renderBlock renders one blank-line-separated chunk of lines, mirroring
// renderBlock() in the TS lib check-for-check, and returns the extended out
// slice. Empty input lines were filtered before this point, so the trailing
// paragraph branch always consumes at least one line — no infinite loop.
func renderBlock(lines []string, out []string) []string {
i := 0
for i < len(lines) {
line := lines[i]
if m := headingRe.FindStringSubmatch(line); m != nil {
level := strconv.Itoa(len(m[1]))
out = append(out, "<h"+level+">"+renderInline(strings.TrimSpace(m[2]))+"</h"+level+">")
i++
continue
}
if hrRe.MatchString(line) {
out = append(out, "<hr>")
i++
continue
}
if strings.HasPrefix(line, "```") {
lang := strings.TrimSpace(line[3:])
var body []string
i++
for i < len(lines) && !strings.HasPrefix(lines[i], "```") {
body = append(body, lines[i])
i++
}
i++ // past the closing fence (or past the end of an unclosed fence)
open := "<pre><code"
if lang != "" {
open += ` class="language-` + escapeHtml(lang) + `"`
}
out = append(out, open+">"+escapeHtml(strings.Join(body, "\n"))+"</code></pre>")
continue
}
if strings.HasPrefix(line, "> ") {
var quoted []string
for i < len(lines) && strings.HasPrefix(lines[i], "> ") {
quoted = append(quoted, lines[i][2:])
i++
}
inner := renderBlock(quoted, nil)
out = append(out, "<blockquote>\n"+strings.Join(inner, "\n")+"\n</blockquote>")
continue
}
if ulRe.MatchString(line) {
var items []string
for i < len(lines) && ulRe.MatchString(lines[i]) {
items = append(items, "<li>"+renderInline(ulRe.ReplaceAllString(lines[i], ""))+"</li>")
i++
}
out = append(out, "<ul>\n"+strings.Join(items, "\n")+"\n</ul>")
continue
}
if olRe.MatchString(line) {
var items []string
for i < len(lines) && olRe.MatchString(lines[i]) {
items = append(items, "<li>"+renderInline(olRe.ReplaceAllString(lines[i], ""))+"</li>")
i++
}
out = append(out, "<ol>\n"+strings.Join(items, "\n")+"\n</ol>")
continue
}
var para []string
for i < len(lines) && !isBlockStart(lines[i]) {
para = append(para, renderInline(strings.TrimSpace(lines[i])))
i++
}
out = append(out, "<p>"+strings.Join(para, "\n")+"</p>")
}
return out
}
// MarkdownToHtml converts the supported Markdown subset to HTML. It is the Go
// twin of markdownToHtml() in src/lib/markdown-to-html.ts and must agree with
// it on every shared vector. Never fails: empty or whitespace-only input
// yields the zero Result (Output:"") — the tool shows nothing — not an error,
// and Error stays empty for every input.
func MarkdownToHtml(raw string) Result {
text := strings.TrimSpace(crlf.ReplaceAllString(raw, "\n"))
if text == "" {
return Result{}
}
var out []string
for _, block := range blockSplit.Split(text, -1) {
var lines []string
for _, l := range strings.Split(block, "\n") {
if strings.TrimSpace(l) != "" {
lines = append(lines, l)
}
}
out = renderBlock(lines, out)
}
return Result{Output: strings.Join(out, "\n")}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →