ecodash/src/main/main.go

75 lines
1.6 KiB
Go
Raw Normal View History

2022-10-15 17:58:44 +00:00
package main
import (
"log"
2023-05-01 16:33:15 +00:00
"net/http"
2022-10-15 17:58:44 +00:00
"os"
"time"
2023-05-01 16:33:15 +00:00
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html"
"github.com/robfig/cron/v3"
2023-05-01 17:39:12 +00:00
"git.massivebox.net/ecodash/ecodash/src/ecodash"
"git.massivebox.net/ecodash/ecodash/src/tools"
2022-10-15 17:58:44 +00:00
)
func main() {
2023-05-01 17:39:12 +00:00
config, isFirstRun, err := ecodash.LoadConfig()
2022-10-15 17:58:44 +00:00
if err != nil {
log.Fatal(err)
}
if !isFirstRun {
cr := cron.New()
2023-05-01 17:39:12 +00:00
_, err = cr.AddFunc("@hourly", config.UpdateHistory)
2022-10-15 17:58:44 +00:00
if err != nil {
log.Fatal(err)
2022-10-15 17:58:44 +00:00
}
cr.Start()
2023-05-01 17:39:12 +00:00
config.UpdateHistory()
2022-10-15 17:58:44 +00:00
}
engine := html.New("./templates/"+config.Dashboard.Theme, ".html")
2023-05-01 17:39:12 +00:00
engine.AddFunc("divide", tools.TemplateDivide)
engine.AddFunc("HTMLDateFormat", tools.TemplateHTMLDateFormat)
2022-10-15 17:58:44 +00:00
app := fiber.New(fiber.Config{
Views: engine,
})
app.Static("/assets", "./templates/"+config.Dashboard.Theme+"/assets")
app.Get("/", func(c *fiber.Ctx) error {
if isFirstRun {
c.Cookie(&fiber.Cookie{Name: "admin_username", Value: ""})
2023-05-01 17:39:12 +00:00
c.Cookie(&fiber.Cookie{Name: "admin_password_hash", Value: tools.Hash("")})
return config.RenderAdminPanel(c)
2022-10-15 17:58:44 +00:00
}
2023-05-01 17:39:12 +00:00
return config.RenderIndex(c)
2022-10-15 17:58:44 +00:00
})
app.Get("/accuracy-notice", func(c *fiber.Ctx) error {
2023-05-01 17:39:12 +00:00
return c.Render("accuracy-notice", config.TemplateDefaultsMap(), "base")
2022-10-15 17:58:44 +00:00
})
2023-05-01 17:39:12 +00:00
app.All("/admin", config.AdminEndpoint)
2022-10-15 17:58:44 +00:00
app.Get("/restart", func(c *fiber.Ctx) error {
2023-05-01 17:39:12 +00:00
if config.IsAuthorized(c) {
2022-10-15 17:58:44 +00:00
go func() {
time.Sleep(time.Second)
os.Exit(1)
}()
2023-05-01 17:39:12 +00:00
return c.Render("restart", config.TemplateDefaultsMap(), "base")
2022-10-15 17:58:44 +00:00
}
2023-05-01 16:33:15 +00:00
return c.Redirect("./", http.StatusTemporaryRedirect)
2022-10-15 17:58:44 +00:00
})
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
log.Fatal(app.Listen(":" + port))
}