Products app

This commit is contained in:
Eden Kirin
2024-01-14 11:47:50 +01:00
parent ff375ae3e8
commit 304ce0678a
17 changed files with 492 additions and 1 deletions

5
products/app/api/dto.go Normal file
View File

@ -0,0 +1,5 @@
package api
type PingDto struct {
Message string `json:"message"`
}

View File

@ -0,0 +1,37 @@
package api
import (
"net/http"
"github.com/gin-gonic/gin"
)
func isError(c *gin.Context, err error) bool {
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"details": err.Error(),
})
return true
}
return false
}
func raiseError(c *gin.Context, errCode int, message string) {
c.AbortWithStatusJSON(errCode, gin.H{
"details": message,
})
}
func raiseBadRequestError(c *gin.Context, message string) {
raiseError(c, http.StatusBadRequest, message)
}
func raiseNotFoundError(c *gin.Context, message string) {
raiseError(c, http.StatusNotFound, message)
}
func raiseInternalError(c *gin.Context, message string) {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"details": "Internal server error. We will we will fix it!",
})
}

View File

@ -0,0 +1,7 @@
package api
import "products/app/db"
type GetProductsResponse struct {
Products []db.Product `json:"products"`
}

View File

@ -0,0 +1,75 @@
package api
import (
"fmt"
"net/http"
"products/app/db"
"strconv"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
const HOST = "0.0.0.0"
const PORT = 3000
func handlePing(c *gin.Context) {
c.JSON(
http.StatusOK,
PingDto{
Message: "Pong!",
},
)
}
func handleGetProducts(dbConn *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
products := db.GetProducts(dbConn)
c.JSON(
http.StatusOK,
GetProductsResponse{
Products: *products,
},
)
}
}
func handleGetProduct(dbConn *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
productId, err := strconv.Atoi(c.Param("productId"))
if err != nil {
raiseBadRequestError(c, "Invalid productId parameter")
return
}
product, err := db.GetProduct(dbConn, productId)
if err != nil {
raiseNotFoundError(c, "Product not found")
return
}
c.JSON(
http.StatusOK,
product,
)
}
}
func initRouter(dbConn *gorm.DB) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
router.GET("/ping", handlePing)
router.GET("/", handleGetProducts(dbConn))
router.GET("/:productId", handleGetProduct(dbConn))
return router
}
func Serve(dbConn *gorm.DB) {
serverAddr := fmt.Sprintf("%s:%d", HOST, PORT)
router := initRouter(dbConn)
router.Run(serverAddr)
}