Working with Markdown in Go (Golang): From Parsing to Customization
Markdown is one of the most popular markup languages for documentation, blogs, and educational materials. In the Go (Golang) ecosystem, there are several powerful libraries that allow you to parse Markdown, convert it to HTML, and even add syntax highlighting. In this article, we will cover the key tools: goldmark, blackfriday, and chroma, and also show how to integrate them into real projects.
Why work with Markdown in Go?
Go is a language often chosen for building web servers, APIs, and static site generators. Markdown is ideal for storing content because it:
- Is readable in raw form (even without rendering);
- Is easy to edit;
- Supports embedding code, tables, and images.
Go libraries allow you to convert Markdown into safe HTML code on the fly, which is critical for educational platforms (e.g., pythonlib.ru).
1. goldmark — A Modern and Extensible Parser
goldmark is the reference library for working with Markdown in Go. It supports CommonMark 0.30, GFM (GitHub Flavored Markdown), and is easily extensible through plugins.
Installation:
go get github.com/yuin/goldmarkBasic example of converting Markdown to HTML:
package main
import ( "bytes" "fmt" "github.com/yuin/goldmark")
func main() { source := []byte("# Hello, Go!
This is **bold** text and `code`.") var buf bytes.Buffer if err := goldmark.Convert(source, &buf); err != nil { panic(err) } fmt.Println(buf.String())}Output:
<h1>Hello, Go!</h1><p>This is <strong>bold</strong> text and <code>code</code>.</p>goldmark extensions:
goldmark-meta— parsing YAML metadata (article headers);goldmark-highlighting— code highlighting via Chroma;goldmark-pdf— export to PDF (experimental).
Example using the extension for tables (GFM):
import ( "github.com/yuin/goldmark" "github.com/yuin/goldmark/extension")
func main() { md := goldmark.New( goldmark.WithExtensions(extension.GFM), ) // ... conversion}2. blackfriday — A Time-Tested Parser
blackfriday is one of the first libraries for Markdown in Go. Despite goldmark being considered more modern, blackfriday is still used in many projects (e.g., Hugo).
Installation:
go get github.com/russross/blackfriday/v2Usage example:
package main
import ( "fmt" "github.com/russross/blackfriday/v2")
func main() { input := []byte("## Heading
List:- item 1- item 2") output := blackfriday.Run(input) fmt.Println(string(output))}Features of blackfriday:
- Support for footnotes, definitions, strikethrough;
- Built-in flags for configuring HTML rendering;
- Fewer dependencies than goldmark.
3. Code Highlighting with Chroma
For educational sites, syntax highlighting is critically important. Chroma is a universal syntax analyzer that integrates with goldmark and blackfriday.
Installation:
go get github.com/alecthomas/chroma/v2Integration with goldmark via goldmark-highlighting:
import ( "github.com/yuin/goldmark" highlighting "github.com/yuin