redone web endpoints

This commit is contained in:
William Clark 2022-12-08 09:58:51 +00:00
parent af16831100
commit 8b0db47e29

View File

@ -4,9 +4,11 @@ import (
"fmt"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"th7/data/core"
"th7/ports"
)
@ -16,19 +18,29 @@ type GinAdapter struct {
port int
}
func (g GinAdapter) registerEndpoints() {
func (g *GinAdapter) getRatio() core.Ratio {
return g.corePort.GetRatio()
}
g.router.GET("/ratio", func(c *gin.Context) {
table := g.corePort.GetRatio()
c.JSON(http.StatusOK, table)
})
func (g *GinAdapter) RatioHandler(c *gin.Context) {
ratio := g.getRatio()
c.JSON(http.StatusOK, ratio)
}
g.router.GET("/channels", func(c *gin.Context) {
channels := g.corePort.GetChannels()
func (g *GinAdapter) getChannels() []core.Channel {
return g.corePort.GetChannels()
}
func (g *GinAdapter) ChannelsHandler(c *gin.Context) {
channels := g.getChannels()
c.JSON(http.StatusOK, channels)
})
}
g.router.GET("/channel/:id", func(c *gin.Context) {
func (g *GinAdapter) getChannelByID(id int) (core.Channel, error) {
return g.corePort.GetChannel(id)
}
func (g *GinAdapter) ChannelByIDHandler(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
@ -37,7 +49,7 @@ func (g GinAdapter) registerEndpoints() {
return
}
channel, err := g.corePort.GetChannel(id)
channel, err := g.getChannelByID(id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err,
@ -46,9 +58,29 @@ func (g GinAdapter) registerEndpoints() {
}
c.JSON(http.StatusOK, channel)
}
func (g *GinAdapter) getTimestamp() string {
return time.Now().Format(time.RFC1123)
}
func (g *GinAdapter) TimestampHandler(c *gin.Context) {
ts := g.getTimestamp()
c.JSON(http.StatusOK, gin.H{
"time": ts,
})
}
func (g *GinAdapter) DataHandler(c *gin.Context) {
timestamp := g.getTimestamp()
ratio := g.getRatio()
channels := g.getChannels()
c.JSON(http.StatusOK, gin.H{
"time": timestamp,
"ratio": ratio,
"channels": channels,
})
}
func NewGinAdapter(corePort ports.CorePort, port int) *GinAdapter {
@ -58,7 +90,12 @@ func NewGinAdapter(corePort ports.CorePort, port int) *GinAdapter {
adapter.port = port
adapter.router = gin.Default()
adapter.registerEndpoints()
adapter.router.GET("/ratio", adapter.RatioHandler)
adapter.router.GET("/channels", adapter.ChannelsHandler)
adapter.router.GET("/channel/:id", adapter.ChannelByIDHandler)
adapter.router.GET("/time", adapter.TimestampHandler)
adapter.router.GET("/data", adapter.DataHandler)
return &adapter
}