Converting blog posts from markdown with Goldmark

Goldmark is a Go library for converting CommonMark to HTML.

The HTML renderer only creates a //html/body from the markdown document. The //html/head would have to be generated separately, perhaps via the goldmark-meta extension.

There is no need to specify the title value in the metadata block, since we can pull the /h1 from the parsed document tree as follows:

func main() {
    source := []byte("# A note\n\nSome text ...\n")
    md := goldmark.New()
    doc := md.Parser().Parse(text.NewReader(source))
    title := getTitle(doc, &source)
    body := render(doc, ...)
    printHTML(title, body)
}

func getTitle(doc ast.Node, src *[]byte) string {
    var title string
    err := ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
        log.Printf("kind: %q, text: %q, entering: %v\n", n.Kind(), n.Text(source), entering)
        if !entering {
            return ast.WalkStop, fmt.Errorf("exiting first leaf node; no heading found")
        }
        if h, ok := n.(*ast.Heading); ok {
            if h.Level == 1 {
                title = string(h.Text(*src))
                return ast.WalkStop, nil
            }
            return ast.WalkStop, fmt.Errorf("first heading was not h1 but h%d", h.Level)
        }
        return ast.WalkContinue, nil
    })
    if err != nil { panic(err) }
    return title
}

Note that the h.Text() call also strips any inline markup. So even if the heading contains e.g. italics for a title in a book review, the string to plug into the //html/head/title will be plain text, as it should be.