Home

Awesome

Markdown Parser and HTML Renderer for Go

pkg.go.dev

Package github.com/gomarkdown/markdown is a Go library for parsing Markdown text and rendering as HTML.

It's very fast and supports common extensions.

Tutorial: https://blog.kowalczyk.info/article/cxn3/advanced-markdown-processing-in-go.html

Code examples:

Those examples are also in examples directory.

API Docs:

Usage

To convert markdown text to HTML using reasonable defaults:

package main

import (
	"os"

	"github.com/gomarkdown/markdown"
	"github.com/gomarkdown/markdown/ast"
	"github.com/gomarkdown/markdown/html"
	"github.com/gomarkdown/markdown/parser"

	"fmt"
)

var mds = `# header

Sample text.

[link](http://example.com)
`

func mdToHTML(md []byte) []byte {
	// create markdown parser with extensions
	extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
	p := parser.NewWithExtensions(extensions)
	doc := p.Parse(md)

	// create HTML renderer with extensions
	htmlFlags := html.CommonFlags | html.HrefTargetBlank
	opts := html.RendererOptions{Flags: htmlFlags}
	renderer := html.NewRenderer(opts)

	return markdown.Render(doc, renderer)
}

func main() {
	md := []byte(mds)
	html := mdToHTML(md)

	fmt.Printf("--- Markdown:\n%s\n\n--- HTML:\n%s\n", md, html)
}

Try it online: https://onlinetool.io/goplayground/#txO7hJ-ibeU

For more documentation read this guide

Comparing to other markdown parsers: https://babelmark.github.io/

Sanitize untrusted content

We don't protect against malicious content. When dealing with user-provided markdown, run renderer HTML through HTML sanitizer such as Bluemonday.

Here's an example of simple usage with Bluemonday:

import (
    "github.com/microcosm-cc/bluemonday"
    "github.com/gomarkdown/markdown"
)

// ...
maybeUnsafeHTML := markdown.ToHTML(md, nil, nil)
html := bluemonday.UGCPolicy().SanitizeBytes(maybeUnsafeHTML)

mdtohtml command-line tool

https://github.com/gomarkdown/mdtohtml is a command-line markdown to html converter built using this library.

You can also use it as an example of how to use the library.

You can install it with:

go get -u github.com/gomarkdown/mdtohtml

To run: mdtohtml input-file [output-file]

Features

Extensions

In addition to the standard markdown syntax, this package implements the following extensions:

Users

Some tools using this package: https://pkg.go.dev/github.com/gomarkdown/markdown?tab=importedby

History

markdown is a fork of v2 of https://github.com/russross/blackfriday.

I refactored the API (split into ast/parser/html sub-packages).

Blackfriday itself was based on C implementation sundown which in turn was based on libsoldout.

License

Simplified BSD License