Skip to content

Instantly share code, notes, and snippets.

@tomcam
Created October 12, 2021 23:30
Show Gist options
  • Save tomcam/942342f301c78a20457c0b2e752bbb2b to your computer and use it in GitHub Desktop.
Save tomcam/942342f301c78a20457c0b2e752bbb2b to your computer and use it in GitHub Desktop.
Self-contained demonstration of the outstanding Goldmark markdown converter package
// Demonstrates the goldmark Markdown to HTML converter.
// Reads name of input file from command line, or creates a
// simple Markdown source file named "foo.md".
// Calls goldmark to convert it to HTML.
// Displays results to standard output.
package main
import (
"bytes"
"fmt"
"github.com/yuin/goldmark"
"io/ioutil"
"os"
)
func main() {
// Holds contents of the Markdown file
var input []byte
var err error
filename := "foo.md"
if len(os.Args) == 1 {
// Create a sample Markdown source file
// because none was specified
err = ioutil.WriteFile(filename, []byte("hello, world."), 0644)
if err != nil {
panic(err.Error())
}
} else {
// Use the source file specified on the command line
filename = os.Args[1]
}
// Read the whole file ito memory.
input, err = ioutil.ReadFile(filename)
if err != nil {
panic(err.Error())
}
var buf bytes.Buffer
// Convert to Markdown
if err := goldmark.Convert(input, &buf); err != nil {
panic(err.Error())
}
// Convert the generated byte slice to string and display.
fmt.Println(string(buf.Bytes()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment