forked from NuVotifier/go-votifier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
52 lines (45 loc) · 1.03 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
package votifier
import (
"crypto/rand"
"encoding/base64"
"fmt"
"net"
"strconv"
"time"
)
func randomString() (string, error) {
p := make([]byte, 24)
_, err := rand.Read(p)
if err != nil {
return "", err
}
return base64.RawStdEncoding.EncodeToString(p), nil
}
func dial(addr string) (net.Conn, error) {
conn, err := net.DialTimeout("tcp", addr, 3*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to connect to %s: %w", addr, err)
}
err = conn.SetDeadline(timeNow().Add(3 * time.Second))
if err != nil {
return nil, fmt.Errorf("failed to set deadline: %v", err)
}
return conn, nil
}
var timeNow = time.Now
func parseTime(unixMillis string) time.Time {
now := timeNow()
ms, err := strconv.ParseInt(unixMillis, 10, 64)
if err == nil {
unix := time.UnixMilli(ms)
// some vote sites don't sent a timestamp,
// fallback to now if older than 1 hour
if now.Sub(unix).Abs() < time.Hour {
return unix
}
}
return now
}
func formatTimeMillis(t time.Time) string {
return strconv.FormatInt(t.UnixMilli(), 10)
}