-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_editor.go
60 lines (51 loc) · 1.07 KB
/
token_editor.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
60
package rewritehtml
import (
"errors"
"io"
)
type TokenEditor struct {
target io.Writer
scanner *Scanner
rewriteFn EditorFunc
done bool
}
// NewTokenEditor will return a TokenEditor that will inspect each Write call
// and rewrite the HTML document before passing it on to w.
func NewTokenEditor(w io.Writer, rewriteFn EditorFunc) *TokenEditor {
return &TokenEditor{
target: w,
scanner: NewScanner(),
rewriteFn: rewriteFn,
}
}
func (i *TokenEditor) doWrite(atEOF bool) error {
for !i.done {
raw, token, err := i.scanner.Next(atEOF)
if !atEOF && errors.Is(err, io.ErrNoProgress) {
break
}
if err != nil {
return err
}
var data []byte
data, i.done = i.rewriteFn(raw, token)
if data == nil {
data = raw
}
_, err = i.target.Write(data)
}
if i.done {
_, _ = io.Copy(i.target, i.scanner.Drain())
}
return nil
}
func (i *TokenEditor) Write(p []byte) (int, error) {
if i.done {
return i.target.Write(p)
}
i.scanner.Concat(p)
return len(p), i.doWrite(false)
}
func (i *TokenEditor) Close() error {
return i.doWrite(true)
}