generated from fluffy-bunny/fluffycore-grpc-starterkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
69 lines (61 loc) · 1.69 KB
/
utils.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
package utils
import (
"encoding/base64"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"net/mail"
"time"
echo "github.com/labstack/echo/v4"
i18n "github.com/nicksnyder/go-i18n/v2/i18n"
)
func GetMyRootPath(c echo.Context) string {
return fmt.Sprintf("%s://%s", c.Scheme(), c.Request().Host)
}
func IsValidEmailAddress(address string) (string, bool) {
addr, err := mail.ParseAddress(address)
if err != nil {
return "", false
}
return addr.Address, true
}
func DeleteCookie(c echo.Context, name string) {
cookie := &http.Cookie{
Name: name,
Value: "",
Path: "/",
MaxAge: -1,
}
c.SetCookie(cookie)
}
func SetCookieInterface(c echo.Context, cookie *http.Cookie, value interface{}) {
cookieData, _ := json.Marshal(value)
encodedValue := base64.StdEncoding.EncodeToString([]byte(cookieData))
cookie.Value = encodedValue
c.SetCookie(cookie)
}
func GetCookieInterface(c echo.Context, name string, v any) error {
cookie, err := c.Cookie(name)
if err != nil {
return err
}
decodedValue, err := base64.StdEncoding.DecodeString(cookie.Value)
if err != nil {
return err
}
return json.Unmarshal(decodedValue, v)
}
func GetLocalizerFromEchoContext(b *i18n.Bundle, e echo.Context) *i18n.Localizer {
accept := e.Request().Header.Get("Accept-Language")
return i18n.NewLocalizer(b, accept)
}
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
func GenerateRandomAlphaNumericString(length int) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}