-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathext_imgvalidator.go
53 lines (42 loc) · 1.43 KB
/
ext_imgvalidator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package markdown
import (
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/text"
"github.com/yuin/goldmark/util"
)
// ImageValidatorFunc validates image URLs. It should return `true` for any valid image URL.
type ImageValidatorFunc func(uri string) (ok bool)
// imgValidatorTransformer implements ASTTransformer
type imgValidatorTransformer struct {
valFunc ImageValidatorFunc
}
// Transform iterate on `ast.Image` nodes and validate images URLs.
func (t *imgValidatorTransformer) Transform(doc *ast.Document, reader text.Reader, pc parser.Context) {
if t.valFunc == nil {
return
}
ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
img, ok := node.(*ast.Image)
if !ok {
return ast.WalkContinue, nil
}
if !t.valFunc(string(img.Destination)) {
img.Destination = []byte{} // Erase destination
}
return ast.WalkContinue, nil
})
}
type imgValidatorExtension struct{}
// ExtImageValidator is a Goldmark extension that pre validation on image URLs.
var ExtImageValidator = &imgValidatorExtension{}
// Extend adds the ExtImageValidator to the provided Goldmark markdown processor
func (l *imgValidatorExtension) Extend(m goldmark.Markdown, valFunc ImageValidatorFunc) {
m.Parser().AddOptions(parser.WithASTTransformers(
util.Prioritized(&imgValidatorTransformer{valFunc}, 500),
))
}