summaryrefslogtreecommitdiff
path: root/utils/utils.go
diff options
context:
space:
mode:
authorSteven Le Rouzic <steven.lerouzic@gmail.com>2024-04-21 22:52:21 +0200
committerSteven Le Rouzic <steven.lerouzic@gmail.com>2024-04-21 22:52:21 +0200
commitbaad75737135eced6f33fecc1c4104f70719c0ce (patch)
treeb8b6a8aa13252168c08a41537458747893ee12d7 /utils/utils.go
parent6e3c40ccb5597a93c3e9d9b4766005c6de424f85 (diff)
Finish the big cleanup
Diffstat (limited to 'utils/utils.go')
-rw-r--r--utils/utils.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/utils/utils.go b/utils/utils.go
new file mode 100644
index 0000000..607236d
--- /dev/null
+++ b/utils/utils.go
@@ -0,0 +1,58 @@
+package utils
+
+import (
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "strconv"
+ "strings"
+ "time"
+)
+
+func GenerateRandomString(len int) (string, error) {
+ bin := make([]byte, len)
+ _, err := rand.Read(bin)
+ if err != nil {
+ return "", err
+ }
+ return base64.StdEncoding.EncodeToString(bin), nil
+}
+
+func ParseNumber(s string) (int64, error) {
+ s = strings.TrimSpace(s)
+ if len(s) == 0 {
+ s = "0"
+ }
+
+ return strconv.ParseInt(s, 10, 64)
+}
+
+func ParseDuration(value string) (time.Duration, error) {
+ const nullDuration = time.Duration(0)
+ if len(value) == 0 {
+ return nullDuration, errors.New("Empty duration string")
+ }
+
+ var unit time.Duration
+ switch value[len(value)-1] {
+ case 's':
+ unit = time.Second
+ case 'm':
+ unit = time.Minute
+ case 'h':
+ unit = time.Hour
+ case 'd':
+ unit = time.Duration(24) * time.Hour
+ case 'w':
+ unit = time.Duration(24*7) * time.Hour
+ default:
+ return nullDuration, errors.New("Invalid duration format")
+ }
+
+ amount, err := strconv.ParseInt(value[0:len(value)-1], 10, 64)
+ if err != nil || amount < 0 {
+ return nullDuration, errors.New("Invalid duration value")
+ }
+
+ return time.Duration(amount) * unit, nil
+}