/
text.go
59 lines (47 loc) · 1.11 KB
/
text.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
54
55
56
57
58
59
package parsers
import (
"io"
"regexp"
"strings"
"github.com/gonzxlez/colibri"
)
// TextRegexp contains a regular expression that matches the MIME type plain text.
const TextRegexp = `^text\/plain`
type TextNode struct {
data []byte
}
func ParseText(resp colibri.Response) (*TextNode, error) {
b, err := io.ReadAll(resp.Body())
if err != nil {
return nil, err
}
return &TextNode{b}, nil
}
func (text *TextNode) Find(expr, exprType string) (Node, error) {
if (exprType != "") && !strings.EqualFold(exprType, RegularExpr) {
return nil, ErrExprType
}
re, err := regexp.Compile(expr)
if err != nil {
return nil, err
}
data := re.Find(text.data)
return &TextNode{data}, nil
}
func (text *TextNode) FindAll(expr, exprType string) ([]Node, error) {
if (exprType != "") && !strings.EqualFold(exprType, RegularExpr) {
return nil, ErrExprType
}
re, err := regexp.Compile(expr)
if err != nil {
return nil, err
}
var nodes []Node
for _, data := range re.FindAll(text.data, -1) {
nodes = append(nodes, &TextNode{data})
}
return nodes, nil
}
func (text *TextNode) Value() any {
return string(text.data)
}