From 7a1abb366a26db8283df0db3e5d605642a146c14 Mon Sep 17 00:00:00 2001 From: razramon Date: Thu, 28 Nov 2024 09:10:42 +0000 Subject: [PATCH] add getItemById with route --- backend/main.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/backend/main.go b/backend/main.go index fb8661b6..bd4bf301 100644 --- a/backend/main.go +++ b/backend/main.go @@ -3,6 +3,7 @@ package main import ( "net/http" "github.com/gin-gonic/gin" + "strconv" ) type Item struct { @@ -23,12 +24,12 @@ func main() { router.GET("/", greet) router.HEAD("/healthcheck", healthcheck) router.GET("/items", getItems) + router.GET("/items/:id", getItemById) router.POST("/items", postItems) - + router.Run() } - func getItems(c *gin.Context){ c.IndentedJSON(http.StatusOK, items) } @@ -44,6 +45,21 @@ func postItems(c *gin.Context){ c.IndentedJSON(http.StatusCreated, newItem) } +func getItemById(c *gin.Context){ + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.IndentedJSON(http.StatusInternalServerError, "Atoi failed") + return + } + for _, item := range items { + if item.ID == id { + c.IndentedJSON(http.StatusOK, item) + return + } + } + c.IndentedJSON(http.StatusNotFound, gin.H{"message": "item not found"}) +} + func greet(c *gin.Context) { c.IndentedJSON(http.StatusOK, "Welcome, Go navigator, to the Anythink cosmic catalog.") }