forked from asciimoo/wuzz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
55 lines (49 loc) · 1.29 KB
/
json.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
package formatter
import (
"bytes"
"errors"
"io"
"github.com/nwidger/jsoncolor"
"github.com/tidwall/gjson"
)
type jsonFormatter struct {
parsedBody gjson.Result
TextFormatter
}
func (f *jsonFormatter) Format(writer io.Writer, data []byte) error {
jsonFormatter := jsoncolor.NewFormatter()
jsonFormatter.Indent = " "
buf := bytes.NewBuffer(make([]byte, 0, len(data)))
err := jsonFormatter.Format(buf, data)
if err == nil {
writer.Write(buf.Bytes())
return nil
}
return errors.New("json formatter error")
}
func (f *jsonFormatter) Title() string {
return "[json]"
}
func (f *jsonFormatter) Search(q string, body []byte) ([]string, error) {
if q != "" {
if f.parsedBody.Type != gjson.JSON {
f.parsedBody = gjson.ParseBytes(body)
}
searchResult := f.parsedBody.Get(q)
if searchResult.Type == gjson.Null {
return nil, errors.New("Invalid gjson query or no results found")
}
if searchResult.Type != gjson.JSON {
return []string{searchResult.String()}, nil
}
body = []byte(searchResult.String())
}
jsonFormatter := jsoncolor.NewFormatter()
jsonFormatter.Indent = " "
buf := bytes.NewBuffer(make([]byte, 0, len(body)))
err := jsonFormatter.Format(buf, body)
if err != nil {
return nil, errors.New("Invalid results")
}
return []string{string(buf.Bytes())}, nil
}