This commit is contained in:
User
2025-01-04 14:04:53 +03:00
parent cdca2437b9
commit 4393a97a95
41 changed files with 23557 additions and 2 deletions

47
frontend/cookie/cookie.go Normal file
View File

@@ -0,0 +1,47 @@
package cookies
import (
"encoding/base64"
"errors"
"net/http"
)
var (
ErrValueTooLong = errors.New("cookie value too long")
ErrInvalidValue = errors.New("invalid cookie value")
)
func Write(w http.ResponseWriter, cookie http.Cookie) error {
// Encode the cookie value using base64.
cookie.Value = base64.URLEncoding.EncodeToString([]byte(cookie.Value))
// Check the total length of the cookie contents. Return the ErrValueTooLong
// error if it's more than 4096 bytes.
if len(cookie.String()) > 4096 {
return ErrValueTooLong
}
// Write the cookie as normal.
http.SetCookie(w, &cookie)
return nil
}
func Read(r *http.Request, name string) (string, error) {
// Read the cookie as normal.
cookie, err := r.Cookie(name)
if err != nil {
return "", err
}
// Decode the base64-encoded cookie value. If the cookie didn't contain a
// valid base64-encoded value, this operation will fail and we return an
// ErrInvalidValue error.
value, err := base64.URLEncoding.DecodeString(cookie.Value)
if err != nil {
return "", ErrInvalidValue
}
// Return the decoded cookie value.
return string(value), nil
}