import (
"gofiber/src/configs"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Name string `json:"name" validate:"required,min=3,max=100"`
Price float64 `json:"price" validate:"required,min=0"`
Stock int `json:"stock" validate:"required,min=0"`
CategoryID uint `json:"category_id"`
Category Category `gorm:"foreignKey:CategoryID"`
}
src/controllers/ProductControllers.go
package controllers
import (
"fmt"
"strconv"
"github.com/gofiber/fiber/v2"
"gofiber/src/helpers"
"gofiber/src/models"
)
func CreateProduct(c *fiber.Ctx) error {
var newProduct models.Product
if err := c.BodyParser(&newProduct); err != nil {
c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Invalid request body",
})
return err
}
errors := helpers.ValidateStruct(newProduct)
if len(errors) > 0 {
return c.Status(fiber.StatusUnprocessableEntity).JSON(errors)
}
models.PostProduct(&newProduct)
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"message": "Product created successfully",
})
}
func UpdateProduct(c *fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
var updatedProduct models.Product
if err := c.BodyParser(&updatedProduct); err != nil {
c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Invalid request body",
})
return err
}
errors := helpers.ValidateStruct(updatedProduct)
if len(errors) > 0 {
return c.Status(fiber.StatusUnprocessableEntity).JSON(errors)
}
err := models.UpdateProduct(id, &updatedProduct)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": fmt.Sprintf("Failed to update product with ID %d", id),
})
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"message": fmt.Sprintf("Product with ID %d updated successfully", id),
})
}
Dengan langkah-langkah di atas, Anda telah menambahkan validasi menggunakan github.com/go-playground/validator/v10 untuk model dan controller Anda. Kini aplikasi Anda akan memvalidasi input sebelum melakukan operasi CRUD pada produk dan kategori.