~fmac/pasticcio

fd5e7c581c7aa731aa4cb3fb29dd8fcee7c81507 — Francesco Camuffo a month ago dcd4dea main v0.1.13
Controller:Api

Add:
- controller
- routes
- stats handler
3 files changed, 60 insertions(+), 0 deletions(-)

M cmd/server/main.go
A controllers/api.controller.go
A routes/api.route.go
M cmd/server/main.go => cmd/server/main.go +4 -0
@@ 64,6 64,10 @@ func main() {
	wallsR := routes.NewWallsRoutes(wallsC)
	wallsR.WallsAddRoute(router)

	apiC := *controllers.NewApiController(conn, db)
	apiR := routes.NewApiRoutes(apiC)
	apiR.ApiAddRoute(router)

	server.Static("/css", path.Join(config.WebRootPath, "css"))

	log.Fatal(server.Run(config.Address + ":" + config.Port))

A controllers/api.controller.go => controllers/api.controller.go +37 -0
@@ 0,0 1,37 @@
package controllers

import (
	"database/sql"
	"net/http"

	db "fmac.dev/pasticcio/db/sqlc"
	"github.com/gin-gonic/gin"
)

type ApiController struct {
	dbConn *sql.DB
	db     *db.Queries
}

func NewApiController(dbConn *sql.DB, db *db.Queries) *ApiController {
	return &ApiController{dbConn, db}
}

func (ctr *ApiController) Stats(ctx *gin.Context) {
	pastesCount, err := ctr.db.CountPastes(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, err.Error())
		return
	}

	wallsCount, err := ctr.db.CountWalls(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, err.Error())
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"PastesCount": pastesCount,
		"WallsCount":  wallsCount,
	})
}

A routes/api.route.go => routes/api.route.go +19 -0
@@ 0,0 1,19 @@
package routes

import (
	"fmac.dev/pasticcio/controllers"
	"github.com/gin-gonic/gin"
)

type ApiRoute struct {
	apiController controllers.ApiController
}

func NewApiRoutes(apiController controllers.ApiController) ApiRoute {
	return ApiRoute{apiController}
}

func (rou *ApiRoute) ApiAddRoute(rg *gin.RouterGroup) {
	router := rg.Group("/api")
	router.GET("/stats", rou.apiController.Stats)
}