Spaces:
Sleeping
Sleeping
File size: 4,373 Bytes
f8e5603 ed36ffe f8e5603 ed36ffe f8e5603 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | package handler
import (
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Price float64 `json:"price"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type Store struct {
mu sync.Mutex
nextID int
items map[int]Item
}
func NewStore() *Store {
return &Store{
nextID: 1,
items: make(map[int]Item),
}
}
func (s *Store) List() []Item {
s.mu.Lock()
defer s.mu.Unlock()
items := make([]Item, 0, len(s.items))
for _, item := range s.items {
items = append(items, item)
}
sort.Slice(items, func(i, j int) bool {
return items[i].ID > items[j].ID
})
return items
}
func (s *Store) Create(name, description string, price float64) Item {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
item := Item{
ID: s.nextID,
Name: name,
Description: description,
Price: price,
CreatedAt: now,
UpdatedAt: now,
}
s.items[item.ID] = item
s.nextID++
return item
}
func (s *Store) Get(id int) (Item, bool) {
s.mu.Lock()
defer s.mu.Unlock()
item, ok := s.items[id]
return item, ok
}
func (s *Store) Update(id int, name, description string, price float64) (Item, bool) {
s.mu.Lock()
defer s.mu.Unlock()
item, ok := s.items[id]
if !ok {
return Item{}, false
}
item.Name = name
item.Description = description
item.Price = price
item.UpdatedAt = time.Now()
s.items[id] = item
return item, true
}
func (s *Store) Delete(id int) bool {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.items[id]; !ok {
return false
}
delete(s.items, id)
return true
}
type API struct {
store *Store
}
func NewAPI() *API {
return &API{store: NewStore()}
}
func (a *API) Routes() *gin.Engine {
router := gin.Default()
api := router.Group("/api")
api.GET("/items", a.listItems)
api.POST("/items", a.createItem)
api.GET("/items/:id", a.getItem)
api.PUT("/items/:id", a.updateItem)
api.DELETE("/items/:id", a.deleteItem)
router.Static("/assets", "ui/dist/assets")
router.StaticFile("/vite.svg", "ui/dist/vite.svg")
router.GET("/", func(c *gin.Context) {
c.File("ui/dist/index.html")
})
router.NoRoute(func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/api") {
respondError(c, http.StatusNotFound, "not found")
return
}
c.File("ui/dist/index.html")
})
return router
}
type itemInput struct {
Name string `json:"name"`
Description string `json:"description"`
Price float64 `json:"price"`
}
func (a *API) listItems(c *gin.Context) {
items := a.store.List()
respondSuccess(c, items)
}
func (a *API) createItem(c *gin.Context) {
var input itemInput
if err := c.ShouldBindJSON(&input); err != nil {
respondError(c, http.StatusBadRequest, err.Error())
return
}
item := a.store.Create(input.Name, input.Description, input.Price)
respondSuccess(c, item)
}
func (a *API) getItem(c *gin.Context) {
id, ok := parseIDParam(c)
if !ok {
return
}
item, found := a.store.Get(id)
if !found {
respondError(c, http.StatusNotFound, "item not found")
return
}
respondSuccess(c, item)
}
func (a *API) updateItem(c *gin.Context) {
id, ok := parseIDParam(c)
if !ok {
return
}
var input itemInput
if err := c.ShouldBindJSON(&input); err != nil {
respondError(c, http.StatusBadRequest, err.Error())
return
}
item, found := a.store.Update(id, input.Name, input.Description, input.Price)
if !found {
respondError(c, http.StatusNotFound, "item not found")
return
}
respondSuccess(c, item)
}
func (a *API) deleteItem(c *gin.Context) {
id, ok := parseIDParam(c)
if !ok {
return
}
if !a.store.Delete(id) {
respondError(c, http.StatusNotFound, "item not found")
return
}
respondSuccess(c, nil)
}
func parseIDParam(c *gin.Context) (int, bool) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil || id <= 0 {
respondError(c, http.StatusNotFound, "item not found")
return 0, false
}
return id, true
}
func respondSuccess(c *gin.Context, data any) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": data,
})
}
func respondError(c *gin.Context, status int, message string) {
c.JSON(status, gin.H{
"code": status,
"msg": message,
"data": nil,
})
}
|