From fde6f4b12b5d8b2c6c1cd203f0383fb5300b2df4 Mon Sep 17 00:00:00 2001 From: Shem Date: Tue, 15 Oct 2024 11:08:31 +0000 Subject: [PATCH] Add endpoint to add items --- backend/main.go | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/backend/main.go b/backend/main.go index e767d53..89a001b 100644 --- a/backend/main.go +++ b/backend/main.go @@ -5,10 +5,19 @@ import ( "github.com/gin-gonic/gin" ) +var items = []gin.H{ + {"id": 1, "name": "Galactic Goggles"}, + {"id": 2, "name": "Meteor Muffins"}, + {"id": 3, "name": "Alien Antenna Kit"}, + {"id": 4, "name": "Starlight Lantern"}, + {"id": 5, "name": "Quantum Quill"}, +} + func main() { router := gin.Default() router.GET("/", greet) router.GET("/items", getItems) + router.POST("/items", addItem) router.HEAD("/healthcheck", healthcheck) router.Run() @@ -25,12 +34,22 @@ func healthcheck(c *gin.Context) { } func getItems(c *gin.Context) { - items := []gin.H{ - {"id": 1, "name": "Galactic Goggles"}, - {"id": 2, "name": "Meteor Muffins"}, - {"id": 3, "name": "Alien Antenna Kit"}, - {"id": 4, "name": "Starlight Lantern"}, - {"id": 5, "name": "Quantum Quill"}, - } c.JSON(http.StatusOK, items) } + +func addItem(c *gin.Context) { + var newItem struct { + Name string `json:"name" binding:"required"` + } + + if err := c.ShouldBindJSON(&newItem); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + id := len(items) + 1 + item := gin.H{"id": id, "name": newItem.Name} + items = append(items, item) + + c.JSON(http.StatusOK, item) +}