feat: validation on articles

This commit is contained in:
Florian Sylvain
2023-08-09 18:13:03 +02:00
parent 836847e9b2
commit 1d1adfdfc7
2 changed files with 14 additions and 3 deletions
+13 -3
View File
@@ -1,7 +1,6 @@
package api package api
import ( import (
. "GohCMS2/domain/article"
. "GohCMS2/useCases" . "GohCMS2/useCases"
"encoding/json" "encoding/json"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
@@ -9,6 +8,11 @@ import (
"strconv" "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) { func getArticle(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32) id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
if err != nil { if err != nil {
@@ -27,10 +31,16 @@ func getArticle(w http.ResponseWriter, r *http.Request) {
} }
func postArticle(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) err := json.NewDecoder(r.Body).Decode(&article)
if err != nil { 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 return
} }
+1
View File
@@ -23,6 +23,7 @@ type UserLogin struct {
var TokenAuth *jwtauth.JWTAuth 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 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." const bodyErrorMessage = "The request cannot be processed due to a mismatch in the format of the body."