-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
utils.go
118 lines (99 loc) · 1.87 KB
/
utils.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//nolint:errcheck
package serv
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
"os"
"sort"
"strings"
"github.com/dosco/graphjin/internal/jsn"
)
// nolint: errcheck
func gqlHash(b string, vars []byte, role string) string {
b = strings.TrimSpace(b)
h := sha256.New()
query := "query"
s, e := 0, 0
space := []byte{' '}
starting := true
var b0, b1 byte
if b == "" {
return ""
}
for {
if starting && b[e] == 'q' {
n := 0
se := e
for e < len(b) && n < len(query) && b[e] == query[n] {
n++
e++
}
if n != len(query) {
io.WriteString(h, strings.ToLower(b[se:e]))
}
}
if e >= len(b) {
break
}
if whitespace(b[e]) {
for e < len(b) && whitespace(b[e]) {
e++
}
if e < len(b) {
b1 = b[e]
}
if alphanum(b0) && alphanum(b1) {
h.Write(space)
}
} else {
starting = false
s = e
for e < len(b) && !whitespace(b[e]) {
e++
}
if e != 0 {
b0 = b[(e - 1)]
}
io.WriteString(h, strings.ToLower(b[s:e]))
}
if e >= len(b) {
break
}
}
if role != "" {
io.WriteString(h, role)
}
if len(vars) == 0 {
return hex.EncodeToString(h.Sum(nil))
}
fields := jsn.Keys([]byte(vars))
sort.Slice(fields, func(i, j int) bool {
return bytes.Compare(fields[i], fields[j]) == -1
})
for i := range fields {
h.Write(fields[i])
}
return hex.EncodeToString(h.Sum(nil))
}
func whitespace(b byte) bool {
return b == ' ' || b == '\n' || b == '\t' || b == ','
}
func alphanum(b byte) bool {
return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9')
}
func isDev() bool {
return strings.HasPrefix(os.Getenv("GO_ENV"), "dev")
}
// Get path relative to cwd
// func relpath(p string) string {
// cwd, err := os.Getwd()
// if err != nil {
// return p
// }
// if strings.HasPrefix(p, cwd) {
// return "./" + strings.TrimLeft(p[len(cwd):], "/")
// }
// return p
// }