File size: 2,010 Bytes
38100fe
 
 
c606a38
51ec421
b5d72d9
c0722d3
b5d72d9
38100fe
 
 
 
c606a38
 
38100fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d3a71d
 
 
 
 
 
 
 
b03de03
 
c0722d3
 
b03de03
 
 
 
b5d72d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c606a38
 
 
 
 
 
 
 
a3619e6
 
 
 
51ec421
 
 
 
 
 
 
 
 
 
 
 
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 utils

import (
	errors "errors"
	"math/rand"
	"os"
	"regexp"
	"strings"
	"time"

	http_error "abdanhafidz.com/go-boilerplate/models/error"
	"github.com/google/uuid"
	"github.com/jackc/pgx/v5/pgconn"
	"gorm.io/gorm"
)

func ToUUID(s any) (uuid.UUID, error) {
	sStr, ok := s.(string)
	if !ok {
		return uuid.UUID{}, http_error.INTERNAL_SERVER_ERROR
	}

	res, err := uuid.Parse(sStr)
	if err != nil {
		return uuid.UUID{}, http_error.INTERNAL_SERVER_ERROR
	}

	return res, nil
}
func CalculateRemainingTime(startTime, dueTime time.Time) int {
	now := time.Now()
	if startTime.After(now) {
		return int(dueTime.Sub(startTime).Seconds())
	}
	remaining := int(dueTime.Sub(now).Seconds())
	if remaining < 0 {
		return 0
	}
	return remaining / 60
}

func Ptr[T any](v T) *T {
	return &v
}

func TimePtrToString(t *time.Time) *string {
	if t == nil {
		return nil
	}
	s := t.Format(time.RFC3339)
	return &s
}

func ValidateCode(code string) error {
	var CodeRegex = regexp.MustCompile(`^[a-zA-Z0-9]{6,12}$`)
	if !CodeRegex.MatchString(code) {
		return http_error.INVALID_CODE
	}
	return nil
}

func GetEnv(key string) string {
	// 1. Normal env
	if val := os.Getenv(key); val != "" {
		return val
	}

	// 2. File-based secret
	if file := os.Getenv(key + "_FILE"); file != "" {
		data, err := os.ReadFile(file)
		if err == nil {
			return strings.TrimSpace(string(data))
		} else {
			panic(err)
		}
	}

	return ""
}

func IsDuplicateKeyError(err error) bool {
	if errors.Is(err, gorm.ErrDuplicatedKey) {
		return true
	}
	var pgErr *pgconn.PgError
	return errors.As(err, &pgErr) && pgErr.Code == "23505"
}

func NormalizeCodeAnswer(ans string) string {
	return strings.ReplaceAll(strings.ToLower(ans), " ", "")
}

func GenerateRandomCode() string {
	const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	const codeLength = 8

	rand.Seed(time.Now().UnixNano())
	code := make([]byte, codeLength)
	for i := range code {
		code[i] = chars[rand.Intn(len(chars))]
	}
	return string(code)
}