api/server/main.go

87 lines
1.5 KiB
Go
Raw Permalink Normal View History

2018-05-14 14:19:29 +02:00
package main
import (
2018-06-08 13:06:20 +02:00
"strconv"
2018-05-14 14:19:29 +02:00
"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)
2018-05-28 14:41:13 +02:00
pq := e.Group(`/pq`)
pq.GET(`/count`, count)
pq.GET(`/list`, listAttr)
2018-06-08 13:06:20 +02:00
pq.GET(`/meters`, listMeters)
2018-05-28 14:17:59 +02:00
for _, v := range app.GetAttributes() {
2018-06-08 13:06:20 +02:00
pq.GET(`/:meter/`+strings.ToLower(v.Name)+`/:date`, getAttr(v.Index))
2018-05-28 14:41:13 +02:00
attrs = append(attrs, strings.ToLower(v.Name))
2018-05-28 14:17:59 +02:00
}
2018-05-14 14:19:29 +02:00
2018-06-11 12:59:14 +02:00
t := e.Group(`/trading`)
t.GET(`/:meter/scores`, getScores)
2018-05-14 14:19:29 +02:00
panic(e.Start(`localhost:33333`))
}
func count(c echo.Context) error {
return c.JSON(200, app.Count())
}
2018-05-28 14:41:13 +02:00
var attrs []string
func listAttr(c echo.Context) error {
return c.JSON(200, attrs)
}
2018-06-08 13:06:20 +02:00
func listMeters(c echo.Context) error {
return c.JSON(200, app.GetMeters())
}
2018-05-28 14:17:59 +02:00
func getAttr(index int) echo.HandlerFunc {
return func(c echo.Context) error {
2018-06-08 13:06:20 +02:00
meter, err := strconv.Atoi(c.Param(`meter`))
if err != nil {
return c.NoContent(400)
}
2018-05-28 14:17:59 +02:00
date, err := time.Parse(time.RFC3339, c.Param(`date`))
if err != nil {
return c.NoContent(400)
}
2018-05-14 14:19:29 +02:00
2018-06-08 13:06:20 +02:00
return c.JSON(200, app.GetAttribute(index, meter, date))
2018-05-14 14:19:29 +02:00
}
2018-05-22 12:07:18 +02:00
}
2018-06-11 12:59:14 +02:00
func getScores(c echo.Context) error {
meter, err := strconv.Atoi(c.Param(`meter`))
if err != nil {
return c.NoContent(400)
}
return c.JSON(200, app.GetScores(meter))
}