go-web-demo / internal /handler /handler.go
DW111D's picture
dockerfile
ed36ffe
Raw History Blame Contribute Delete
4.37 kB
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,
})
}