api/server/main.go

75 lines
1.3 KiB
Go

package main
import (
"strconv"
"strings"
"time"
"git.fuyu.moe/5GPowerQuality/api/app"
"git.fuyu.moe/Fuyu/flog"
"github.com/labstack/echo"
)
func main() {
defer func() {
v := recover()
if v != nil {
flog.Critical(`panic: `, v)
}
}()
setLogger()
flog.Info(`Starting`)
catchSignals()
app.InitDB()
e := echo.New()
e.HideBanner = true
e.Use(recoverMiddleware)
pq := e.Group(`/pq`)
pq.GET(`/count`, count)
pq.GET(`/list`, listAttr)
pq.GET(`/meters`, listMeters)
for _, v := range app.GetAttributes() {
pq.GET(`/:meter/`+strings.ToLower(v.Name)+`/:date`, getAttr(v.Index))
attrs = append(attrs, strings.ToLower(v.Name))
}
panic(e.Start(`localhost:33333`))
}
func count(c echo.Context) error {
return c.JSON(200, app.Count())
}
var attrs []string
func listAttr(c echo.Context) error {
return c.JSON(200, attrs)
}
func listMeters(c echo.Context) error {
return c.JSON(200, app.GetMeters())
}
func getAttr(index int) echo.HandlerFunc {
return func(c echo.Context) error {
meter, err := strconv.Atoi(c.Param(`meter`))
if err != nil {
return c.NoContent(400)
}
date, err := time.Parse(time.RFC3339, c.Param(`date`))
if err != nil {
return c.NoContent(400)
}
return c.JSON(200, app.GetAttribute(index, meter, date))
}
}