feat(cookies,errors): error helper for cookie unmarshaling
This commit is contained in:
@@ -33,7 +33,7 @@ func (p *Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
hasCookie := true
|
||||
|
||||
var c DashboardCookie
|
||||
if err := cookies.UnmarshalRequest(r, &c); errors.Is(err, cookies.ErrNoCookie) {
|
||||
if err := cookies.UnmarshalRequest(r, &c); errors.Is(err, cookies.ErrNoCookie{}) {
|
||||
hasCookie = false
|
||||
c = DashboardCookie{Hello: "Hello world", Bool: true, Test: 69420}
|
||||
} else if err != nil {
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"forge.capytal.company/capytalcode/project-comicverse/lib/router/rerrors"
|
||||
)
|
||||
|
||||
type Marshaler interface {
|
||||
@@ -26,9 +28,16 @@ var (
|
||||
ErrUnmarshal = errors.New("Failed to unmarshal JSON value from cookie value")
|
||||
ErrReflectPanic = errors.New("Reflect panic while trying to get tag from value")
|
||||
ErrMissingName = errors.New("Failed to get name of cookie")
|
||||
ErrNoCookie = http.ErrNoCookie
|
||||
)
|
||||
|
||||
type ErrNoCookie struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (e ErrNoCookie) Error() string {
|
||||
return fmt.Sprintf("Cookie \"%s\" missing from request", e.name)
|
||||
}
|
||||
|
||||
var COOKIE_EXPIRE_VALID_FORMATS = []string{
|
||||
time.DateOnly, time.DateTime,
|
||||
time.RFC1123, time.RFC1123Z,
|
||||
@@ -76,13 +85,23 @@ func UnmarshalRequest(r *http.Request, v any) error {
|
||||
}
|
||||
|
||||
c, err := r.Cookie(name)
|
||||
if err != nil {
|
||||
if errors.Is(err, http.ErrNoCookie) {
|
||||
return ErrNoCookie{name}
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return Unmarshal(c, v)
|
||||
}
|
||||
|
||||
func RerrUnmarshalCookie(err error) rerrors.RouteError {
|
||||
if e, ok := err.(ErrNoCookie); ok {
|
||||
return rerrors.MissingCookies([]string{e.name})
|
||||
} else {
|
||||
return rerrors.InternalError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func marshalValue(v any) (*http.Cookie, error) {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user