Files

76 lines
1.3 KiB
Go

// Package api will server the SW data via a JSON REST API.
package api
import (
"net/http"
"strconv"
"github.com/ESilva15/PTInvCertSWDB/config"
sw "github.com/ESilva15/PTInvCertSWDB/sw"
"github.com/gin-gonic/gin"
)
var ginMode = "debug"
func get(c *gin.Context) {
param := c.Param("id")
if param == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "no certNo in request",
"info": "user",
})
return
}
certNo, err := strconv.Atoi(param)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "certNo is not an integer",
"info": "use an integer in the request",
})
return
}
sw, err := sw.Get(certNo)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
c.JSON(http.StatusOK, sw)
}
func count(c *gin.Context) {
count := sw.Count()
c.JSON(http.StatusOK, gin.H{"count": count})
}
func RunServer() error {
cfg := config.GetInstance()
gin.SetMode(ginMode)
router := gin.Default()
authGroup := router.Group("/")
authGroup.Use(APIAuthMiddleWare())
{
authGroup.GET("/sw/:id", get)
authGroup.GET("/count", count)
}
// Star the SW service
err := sw.StartSWService()
if err != nil {
return err
}
err = router.Run(":" + cfg.Port)
if err != nil {
return err
}
return nil
}