Created
April 15, 2022 08:48
-
-
Save Develp10/08fdab8d3a5e23aebf67848cd5f9af59 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package products | |
| import ( | |
| "go-fiber-api-docker/pkg/common/models" | |
| "github.com/gofiber/fiber/v2" | |
| ) | |
| type AddProductRequestBody struct { | |
| Name string `json:"name"` | |
| Stock int32 `json:"stock"` | |
| Price int32 `json:"price"` | |
| } | |
| func (h handler) AddProduct(c *fiber.Ctx) error { | |
| body := AddProductRequestBody{} | |
| // parse body, attach to AddProductRequestBody struct | |
| if err := c.BodyParser(&body); err != nil { | |
| return fiber.NewError(fiber.StatusBadRequest, err.Error()) | |
| } | |
| var product models.Product | |
| product.Name = body.Name | |
| product.Stock = body.Stock | |
| product.Price = body.Price | |
| // insert new db entry | |
| if result := h.DB.Create(&product); result.Error != nil { | |
| return fiber.NewError(fiber.StatusNotFound, result.Error.Error()) | |
| } | |
| return c.Status(fiber.StatusCreated).JSON(&product) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment