70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package http
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"example.com/bridging-sample/api/internal/models"
|
|
"example.com/bridging-sample/api/internal/repo"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type Handlers struct{ Items *repo.ItemRepo }
|
|
|
|
func (h *Handlers) Register(r *gin.Engine) {
|
|
r.GET("/healthz", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
|
|
|
|
r.GET("/items", h.listItems)
|
|
r.GET("/items/:id", h.getItem)
|
|
r.POST("/items", h.createItem)
|
|
r.DELETE("/items/:id", h.deleteItem)
|
|
r.GET("/", getHelloWorld)
|
|
}
|
|
|
|
func (h *Handlers) listItems(c *gin.Context) {
|
|
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
|
|
items, err := h.Items.List(c, int32(limit))
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, items)
|
|
}
|
|
|
|
func getHelloWorld(c *gin.Context) {
|
|
c.IndentedJSON(http.StatusOK, "Hello world")
|
|
}
|
|
|
|
func (h *Handlers) getItem(c *gin.Context) {
|
|
id := c.Param("id")
|
|
item, err := h.Items.Get(c, id)
|
|
if err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, item)
|
|
}
|
|
|
|
func (h *Handlers) createItem(c *gin.Context) {
|
|
var in models.Item
|
|
if err := c.BindJSON(&in); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
id, err := h.Items.Create(c, in)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, gin.H{"id": id})
|
|
}
|
|
|
|
func (h *Handlers) deleteItem(c *gin.Context) {
|
|
if err := h.Items.Delete(c, c.Param("id")); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|