From 1d1adfdfc749f4adc0fbff5363e903956f1e59b1 Mon Sep 17 00:00:00 2001 From: Florian Sylvain Date: Wed, 9 Aug 2023 18:13:03 +0200 Subject: [PATCH] feat: validation on articles --- api/article.go | 16 +++++++++++++--- api/auth.go | 1 + 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/api/article.go b/api/article.go index b8c5914..c868f6c 100644 --- a/api/article.go +++ b/api/article.go @@ -1,7 +1,6 @@ package api import ( - . "GohCMS2/domain/article" . "GohCMS2/useCases" "encoding/json" "github.com/go-chi/chi/v5" @@ -9,6 +8,11 @@ import ( "strconv" ) +type ArticlePost struct { + Title string `json:"title" validate:"required,min=3,max=50"` + Body string `json:"body" validate:"required,max=10000"` +} + func getArticle(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32) if err != nil { @@ -27,10 +31,16 @@ func getArticle(w http.ResponseWriter, r *http.Request) { } func postArticle(w http.ResponseWriter, r *http.Request) { - var article Article + var article ArticlePost err := json.NewDecoder(r.Body).Decode(&article) if err != nil { - http.Error(w, "The request cannot be processed due to a mismatch in the format of the body.", http.StatusBadRequest) + http.Error(w, bodyErrorMessage, http.StatusBadRequest) + return + } + + err = validate.Struct(article) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) return } diff --git a/api/auth.go b/api/auth.go index bd52b13..ec321ac 100644 --- a/api/auth.go +++ b/api/auth.go @@ -23,6 +23,7 @@ type UserLogin struct { var TokenAuth *jwtauth.JWTAuth +// TODO Move into its own file or package that handles api errors const logsErrorMessage = "Access to the requested resource is forbidden due to incorrect password and/or username." const bodyErrorMessage = "The request cannot be processed due to a mismatch in the format of the body."