79 lines
1.3 KiB
Go
79 lines
1.3 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"machines/app/db"
|
|
"net/http"
|
|
"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 handleGetMachines(dbConn *gorm.DB) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
machines := db.GetMachines(dbConn)
|
|
|
|
c.JSON(
|
|
http.StatusOK,
|
|
GetMachinesResponse{
|
|
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()
|
|
|
|
routes := router.Group("/machines")
|
|
{
|
|
routes.GET("/ping", handlePing)
|
|
routes.GET("", handleGetMachines(dbConn))
|
|
routes.GET("/:machineId", handleGetMachine(dbConn))
|
|
}
|
|
|
|
return router
|
|
}
|
|
|
|
func Serve(dbConn *gorm.DB) {
|
|
serverAddr := fmt.Sprintf("%s:%d", HOST, PORT)
|
|
|
|
router := initRouter(dbConn)
|
|
router.Run(serverAddr)
|
|
}
|