feat(forms,errors): error helper for form and query parsing

This commit is contained in:
Guz
2024-10-24 19:39:50 -03:00
parent dd1d67207d
commit 19cf6e13cc
2 changed files with 32 additions and 4 deletions

View File

@@ -4,13 +4,19 @@ import (
"net/http"
"errors"
"log"
"strconv"
"forge.capytal.company/capytalcode/project-comicverse/lib/router/rerrors"
"forge.capytal.company/capytalcode/project-comicverse/lib/cookies"
"forge.capytal.company/capytalcode/project-comicverse/lib/forms"
"forge.capytal.company/capytalcode/project-comicverse/templates/layouts"
)
type Dashboard struct{}
type Dashboard struct {
Message string `form:"message"`
Limit int `form:"limit"`
Optional *string `form:"optional"`
}
type DashboardCookie struct {
Hello string `cookie:"dashboard-cookie"`
@@ -19,6 +25,11 @@ type DashboardCookie struct {
}
func (p *Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := forms.Unmarshal(r, p); err != nil {
forms.RerrUnsmarshal(err).ServeHTTP(w, r)
return
}
hasCookie := true
var c DashboardCookie
@@ -49,9 +60,13 @@ func (p *Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
templ (p *Dashboard) Component() {
@layouts.Page() {
<div class="text-danger-100 font-sans">
<p>Hello world</p>
<p>test</p>
<p>test</p>
<p>{ p.Message }</p>
<p>{ strconv.Itoa(p.Limit) }</p>
if p.Optional != nil {
<p>{ *p.Optional }</p>
} else {
<p>nil</p>
}
</div>
}
}

View File

@@ -9,6 +9,9 @@ import (
"strconv"
"strings"
"forge.capytal.company/capytalcode/project-comicverse/lib/router/rerrors"
)
func Unmarshal(r *http.Request, v any) (err error) {
if u, ok := v.(Unmarshaler); ok {
return u.UnmarshalForm(r)
@@ -91,6 +94,16 @@ func Unmarshal(r *http.Request, v any) (err error) {
return nil
}
func RerrUnsmarshal(err error) rerrors.RouteError {
if e, ok := err.(*ErrMissingRequiredValue); ok {
return rerrors.MissingParameters([]string{e.value})
} else if e, ok := err.(*ErrInvalidValueType); ok {
return rerrors.BadRequest(e.Error())
} else {
return rerrors.InternalError(err)
}
}
func setFieldValue(rv reflect.Value, v string) error {
switch rv.Kind() {