th7/web/gin.go
2022-12-05 14:25:48 +00:00

70 lines
1.1 KiB
Go

package web
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"th7/ports"
)
type GinAdapter struct {
router *gin.Engine
corePort ports.CorePort
port int
}
func (g GinAdapter) registerEndpoints() {
g.router.GET("/ratio", func(c *gin.Context) {
table := g.corePort.GetRatio()
c.JSON(http.StatusOK, table)
})
g.router.GET("/channels", func(c *gin.Context) {
channels := g.corePort.GetChannels()
c.JSON(http.StatusOK, channels)
})
g.router.GET("/channel/:id", func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err,
})
return
}
channel, err := g.corePort.GetChannel(id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err,
})
return
}
c.JSON(http.StatusOK, channel)
})
}
func NewGinAdapter(corePort ports.CorePort, port int) *GinAdapter {
var adapter GinAdapter
adapter.corePort = corePort
adapter.port = port
adapter.router = gin.Default()
adapter.registerEndpoints()
return &adapter
}
func (g *GinAdapter) Run() {
portStr := fmt.Sprintf(":%d", g.port)
g.router.Run(portStr)
}