Add ast.Walk example demonstrating how to process links

This commit is contained in:
Artyom Pervukhin 2019-12-21 12:40:22 +03:00
parent 2aab93edb4
commit 2142442ea9

39
ast/example_test.go Normal file
View file

@ -0,0 +1,39 @@
package ast_test
import (
"fmt"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/text"
)
func ExampleWalk() {
// Extract links from markdown text
src := []byte(`Some links: <https://golang.org/>, [goldmark repo](https://github.com/yuin/goldmark)`)
fn := func(n ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
switch n.Kind() {
case ast.KindLink, ast.KindAutoLink:
default:
return ast.WalkContinue, nil
}
if l, ok := n.(*ast.AutoLink); ok {
fmt.Printf("auto link: %s\n", l.URL(src))
}
if l, ok := n.(*ast.Link); ok {
fmt.Printf("link: %s\n", l.Destination)
}
return ast.WalkContinue, nil
}
node := goldmark.DefaultParser().Parse(text.NewReader(src))
_ = ast.Walk(node, fn)
// Output:
//
// auto link: https://golang.org/
// link: https://github.com/yuin/goldmark
}