Skip to content

Commit

Permalink
Merge pull request #79 from Wilcolab/revert-78-go/3
Browse files Browse the repository at this point in the history
Revert "Refactor item handling and add view count functionality"
  • Loading branch information
shem8 authored Oct 15, 2024
2 parents ecac7c9 + f03d56f commit ecb4b90
Showing 1 changed file with 7 additions and 51 deletions.
58 changes: 7 additions & 51 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,21 @@ package main

import (
"net/http"
"strconv"
"sync"

"github.com/gin-gonic/gin"
)

type Item struct {
ID int `json:"id"`
Name string `json:"name"`
ViewCount int `json:"view_count"`
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"},
}

var (
items = []Item{
{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"},
}
mu sync.Mutex
)

func main() {
router := gin.Default()
router.GET("/", greet)
router.GET("/items", getItems)
router.GET("/items/:id", getItemByID)
router.POST("/items", addItem)
router.HEAD("/healthcheck", healthcheck)

Expand All @@ -50,31 +37,6 @@ func getItems(c *gin.Context) {
c.JSON(http.StatusOK, items)
}

func getItemByID(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid item ID"})
return
}

var item *Item
for i := range items {
if items[i].ID == id {
item = &items[i]
break
}
}

if item == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Item not found"})
return
}

go incrementViewCount(item)

c.JSON(http.StatusOK, item)
}

func addItem(c *gin.Context) {
var newItem struct {
Name string `json:"name" binding:"required"`
Expand All @@ -86,14 +48,8 @@ func addItem(c *gin.Context) {
}

id := len(items) + 1
item := Item{ID: id, Name: newItem.Name}
item := gin.H{"id": id, "name": newItem.Name}
items = append(items, item)

c.JSON(http.StatusOK, item)
}

func incrementViewCount(item *Item) {
mu.Lock()
defer mu.Unlock()
item.ViewCount++
}

0 comments on commit ecb4b90

Please sign in to comment.