Golang Markdown Parsing with Blackfriday Library
Introduction to Parsing Markdown in Golang
In this tutorial, we’re going to delve into how Go (or Golang) can be used to parse Markdown files. If you’re not already familiar with the Markdown syntax, I recommend this comprehensive guide.
Parsing of Markdown in Golang can be accomplished using open source libraries, which will greatly simplify the process. Most libraries will output HTML which can then be styled or processed further.
One such library is blackfriday
, so let’s jump in and look at how it is used.
Parsing Markdown using Blackfriday
Blackfriday library is a Markdown processor implemented in Go. It is compliant with the CommonMark specification and also includes some GitHub-flavored markdown extensions.
First, we need to install the library:
go get -u github.com/russross/blackfriday
Now let’s see how to parse markdown text into HTML:
package main
import (
"fmt"
"github.com/russross/blackfriday"
)
func main() {
// Markdown input as string
input := []byte(`
# Golang Markdown Parsing
- Golang
- Blackfriday
- Markdown
- Parsing
`)
// Parsing markdown to HTML
output := blackfriday.Run(input)
fmt.Println(string(output))
}
Running the above code will return the following HTML:
<h1>Golang Markdown Parsing</h1>
<ul>
<li>Golang</li>
<li>Blackfriday</li>
<li>Markdown</li>
<li>Parsing</li>
</ul>
Parsing Markdown Files
Now, let’s suppose that our Markdown input is in a file. Our goal is to parse that file and output the HTML. This will involve reading in the file as a byte slice which then can be passed to blackfriday.Run
.
package main
import (
"fmt"
"github.com/russross/blackfriday"
"io/ioutil"
"log"
)
func main() {
// Read file contents into byte slice
input, err := ioutil.ReadFile("example.md")
if err != nil {
log.Fatal(err)
}
// Parsing markdown to HTML
output := blackfriday.Run(input)
fmt.Println(string(output))
}
Just replace example.md
with your markdown file, run the code, and you will get the HTML output.
More on Markdown in Golang
While blackfriday
is a great library for general markdown parsing, specific requirements might require other solutions. If you’re rendering markdown in various other languages/frameworks, you might want to refer to other articles on our blog for specifics, like Markdown in React or Markdown in Ruby on Rails.
Wrapping up
That’s it. As you can see, parsing markdown in Go using the Blackfriday library is simple and straightforward. You can now use this know-how to build own Go application and process markdown effectively. Happy coding!