-
Notifications
You must be signed in to change notification settings - Fork 5
/
funcs.go
99 lines (82 loc) · 1.82 KB
/
funcs.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package fir
import (
"bytes"
"encoding/base64"
"fmt"
"html/template"
"io"
"strings"
"github.com/goccy/go-json"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
"github.com/davecgh/go-spew/spew"
"github.com/Masterminds/sprig/v3"
)
func defaultFuncMap() template.FuncMap {
allFuncs := make(template.FuncMap)
for k, v := range sprig.FuncMap() {
allFuncs[k] = v
}
allFuncs["bytesToMap"] = bytesToMap
allFuncs["bytesToString"] = bytesToString
allFuncs["dump"] = dump
allFuncs["toJsonb64"] = toJsonb64
allFuncs["textAreaRows"] = textAreaRows
return allFuncs
}
func textAreaRows(s string) int {
l := len(strings.Split(s, "\n")) + 1
if l < 2 {
return 2
}
if l > 15 {
return 15
}
return l
}
func toJsonb64(data interface{}) (string, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(jsonData), nil
}
func bytesToMap(data []byte) map[string]any {
m := make(map[string]any)
err := json.Unmarshal(data, &m)
if err != nil {
panic(err)
}
return m
}
func bytesToString(data []byte) string {
return string(data)
}
func dump(val any) (template.HTML, error) {
var buf bytes.Buffer
defer buf.Reset()
err := highlight(&buf, spew.Sdump(val), "dracula")
if err != nil {
return "", err
}
return template.HTML(fmt.Sprintf("<code>%v</code>", buf.String())), nil
}
func highlight(w io.Writer, source, style string) error {
// Determine lexer.
l := lexers.Get("go")
l = chroma.Coalesce(l)
// Determine formatter.
f := html.New(html.WithClasses(false))
// Determine style.
s := styles.Get(style)
if s == nil {
s = styles.Fallback
}
it, err := l.Tokenise(nil, source)
if err != nil {
return err
}
return f.Format(w, s, it)
}