This repository has been archived by the owner on Apr 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utility.go
104 lines (94 loc) · 2.05 KB
/
utility.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
package triangulate
import (
"encoding/base64"
"encoding/json"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"syscall"
)
func writeJSON(w http.ResponseWriter, data interface{}, status int) {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(http.StatusText(500))
return
}
}
func writeJSONError(w http.ResponseWriter, message string, status int) {
if message == "" {
message = http.StatusText(status)
}
writeJSON(w, struct {
Error string `json:"error"`
}{
Error: message,
}, status)
}
func base64Encode(message []byte) []byte {
b := make([]byte, base64.StdEncoding.EncodedLen(len(message)))
base64.StdEncoding.Encode(b, message)
return b
}
func base64Decode(message []byte) (b []byte, err error) {
var l int
b = make([]byte, base64.StdEncoding.DecodedLen(len(message)))
l, err = base64.StdEncoding.Decode(b, message)
if err != nil {
return
}
return b[:l], nil
}
func mergeMaps(left, right map[string]string) map[string]string {
for key, rightVal := range right {
if _, present := left[key]; !present {
// key not in left so we can just shove it in
left[key] = rightVal
}
}
return left
}
func closeHandler() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
log.Println("Terminating via terminal")
d, err := db.DB()
if err != nil {
log.Fatal(err)
}
err = d.Close()
if err != nil {
log.Fatal(err)
}
os.Exit(0)
}()
}
func indexOf(word string, data []string) int {
for k, v := range data {
if word == v {
return k
}
}
return -1
}
func generateUniqueId(data []string, len int) string {
id := RandStringRunes(len)
if indexOf(id, data) == -1 {
return id
}
return generateUniqueId(data, len+1)
}
func RandStringRunes(n int) string {
letterRunes := []rune("bcdfghjlmnpqrstvwxz0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}