-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathutil.go
71 lines (60 loc) · 1.28 KB
/
util.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
package util
import (
"bytes"
"crypto/md5"
cryptoRand "crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"strconv"
)
func ToJsonMust(data any) []byte {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
err := encoder.Encode(data)
if err != nil {
log.Fatal(err)
}
return append(bytes.TrimSpace(buffer.Bytes()), '\n')
}
func Md5sum(text string) string {
// Source: <https://stackoverflow.com/a/25286918/151048>.
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
func RandomBytes(n int) []byte {
b := make([]byte, n)
if _, err := cryptoRand.Read(b); err != nil {
fmt.Println("Error: ", err)
return []byte{}
}
return b[:]
}
func RandomString() string {
return hex.EncodeToString(RandomBytes(16))
}
func CommitHashShorten(hash string) string {
if len(hash) > 7 {
return hash[:7]
}
return hash
}
func ComputeFgForBg(c string) string {
rgb, err := strconv.ParseInt(c[1:], 16, 32)
if err != nil {
fmt.Println("Error parsing color:", err)
return "black"
}
r := (rgb >> 16) & 0xff
g := (rgb >> 8) & 0xff
b := rgb & 0xff
luma := 0.2126*float64(r) + 0.7152*float64(g) + 0.0722*float64(b) // per ITU-R BT.709
if luma > 100 {
return "#222e"
} else {
return "#eeee"
}
}