-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighlighter.go
46 lines (39 loc) · 1.17 KB
/
highlighter.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
package jsonhl
import (
"bytes"
"github.com/dawi/jsont"
"io"
"strings"
)
func HighlightString(jsonString string) (string, error) {
return HighlightStringC(jsonString, DefaultColors)
}
func HighlightStringC(jsonString string, colors Colors) (string, error) {
reader := strings.NewReader(jsonString)
writer := &bytes.Buffer{}
err := HighlightC(reader, writer, colors)
return writer.String(), err
}
func HighlightBytes(jsonString []byte, colors Colors) ([]byte, error) {
return HighlightBytesC(jsonString, DefaultColors)
}
func HighlightBytesC(jsonString []byte, colors Colors) ([]byte, error) {
reader := bytes.NewBuffer(jsonString)
writer := &bytes.Buffer{}
err := HighlightC(reader, writer, colors)
return writer.Bytes(), err
}
func Highlight(reader io.Reader, writer io.Writer) error {
return HighlightC(reader, writer, DefaultColors)
}
func HighlightC(reader io.Reader, writer io.Writer, colors Colors) error {
tokenizer := jsont.NewTokenizer(reader)
for tokenizer.Next() {
token := tokenizer.Token()
color := DefaultColors[token.Type]
if _, err := writer.Write([]byte(color + token.Value + resetColor)); err != nil {
return err
}
}
return tokenizer.Error()
}