Machines done
This commit is contained in:
37
machines/app/api/helpers.go
Normal file
37
machines/app/api/helpers.go
Normal 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!",
|
||||
})
|
||||
}
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"machines/app/db"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
@ -24,24 +25,44 @@ func handlePing(c *gin.Context) {
|
||||
func handleGetMachines(dbConn *gorm.DB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
machines := db.GetMachines(dbConn)
|
||||
fmt.Printf("%+v\n", machines)
|
||||
|
||||
c.JSON(
|
||||
http.StatusOK,
|
||||
GetMachinesResponse{
|
||||
Machines: machines,
|
||||
Machines: *machines,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetMachine(dbConn *gorm.DB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
machineId, err := strconv.Atoi(c.Param("machineId"))
|
||||
if err != nil {
|
||||
raiseBadRequestError(c, "Invalid machineId parameter")
|
||||
return
|
||||
}
|
||||
|
||||
machine, err := db.GetMachine(dbConn, machineId)
|
||||
if err != nil {
|
||||
raiseNotFoundError(c, "Machine not found")
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(
|
||||
http.StatusOK,
|
||||
machine,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func initRouter(dbConn *gorm.DB) *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
router := gin.Default()
|
||||
|
||||
router.GET("/ping", handlePing)
|
||||
router.GET("/", handleGetMachines(dbConn))
|
||||
// routes.GET("/machines/:machineId", handleGetMachineDetails)
|
||||
router.GET("/:machineId", handleGetMachine(dbConn))
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user