Skip to content

Commit

Permalink
add getItemById with route
Browse files Browse the repository at this point in the history
  • Loading branch information
razramon committed Nov 28, 2024
1 parent 549c43e commit 7a1abb3
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"net/http"
"github.com/gin-gonic/gin"
"strconv"
)

type Item struct {
Expand All @@ -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)
}
Expand All @@ -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.")
}
Expand Down

0 comments on commit 7a1abb3

Please sign in to comment.