-
Notifications
You must be signed in to change notification settings - Fork 38
/
utils.go
100 lines (91 loc) · 2.38 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
package redisgraph
import (
"crypto/rand"
"fmt"
"strings"
"strconv"
)
// go array to string is [1 2 3] for [1, 2, 3] array
// cypher expects comma separated array
func arrayToString(arr []interface{}) string {
var arrayLength = len(arr)
strArray := []string{}
for i := 0; i < arrayLength; i++ {
strArray = append(strArray, ToString(arr[i]))
}
return "[" + strings.Join(strArray, ",") + "]"
}
// go array to string is [1 2 3] for [1, 2, 3] array
// cypher expects comma separated array
func strArrayToString(arr []string) string {
var arrayLength = len(arr)
strArray := []string{}
for i := 0; i < arrayLength; i++ {
strArray = append(strArray, ToString(arr[i]))
}
return "[" + strings.Join(strArray, ",") + "]"
}
func mapToString(data map[string]interface{}) string {
pairsArray := []string{}
for k, v := range data {
pairsArray = append(pairsArray, k + ": " + ToString(v))
}
return "{" + strings.Join(pairsArray, ",") + "}"
}
func ToString(i interface{}) string {
if(i == nil) {
return "null"
}
switch i.(type) {
case string:
s := i.(string)
return strconv.Quote(s)
case int:
return strconv.Itoa(i.(int))
case float64:
return strconv.FormatFloat(i.(float64), 'f', -1, 64)
case bool:
return strconv.FormatBool(i.(bool))
case []interface{}:
arr := i.([]interface{})
return arrayToString(arr)
case map[string]interface{}:
data := i.(map[string]interface{})
return mapToString(data)
case []string:
arr := i.([]string)
return strArrayToString(arr)
default:
panic("Unrecognized type to convert to string")
}
}
// https://medium.com/@kpbird/golang-generate-fixed-size-random-string-dd6dbd5e63c0
func RandomString(n int) string {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
output := make([]byte, n)
// We will take n bytes, one byte for each character of output.
randomness := make([]byte, n)
// read all random
_, err := rand.Read(randomness)
if err != nil {
panic(err)
}
l := len(letterBytes)
// fill output
for pos := range output {
// get random item
random := uint8(randomness[pos])
// random % 64
randomPos := random % uint8(l)
// put into output
output[pos] = letterBytes[randomPos]
}
return string(output)
}
func BuildParamsHeader(params map[string]interface{}) (string) {
header := "CYPHER "
for key, value := range params {
header += fmt.Sprintf("%s=%v ", key, ToString(value))
}
return header
}