AnthoLume/server/server.go

92 lines
1.5 KiB
Go
Raw Normal View History

2023-09-18 23:57:18 +00:00
package server
import (
2023-11-29 03:01:49 +00:00
"embed"
2023-09-18 23:57:18 +00:00
"net/http"
"sync"
2023-09-18 23:57:18 +00:00
"time"
log "github.com/sirupsen/logrus"
"reichard.io/antholume/api"
"reichard.io/antholume/config"
"reichard.io/antholume/database"
2023-09-18 23:57:18 +00:00
)
type server struct {
db *database.DBManager
api *api.API
done chan int
wg sync.WaitGroup
2023-09-18 23:57:18 +00:00
}
// Create new server
func New(assets *embed.FS) *server {
2023-09-18 23:57:18 +00:00
c := config.Load()
db := database.NewMgr(c)
2023-11-29 03:01:49 +00:00
api := api.NewApi(db, c, assets)
2023-09-18 23:57:18 +00:00
return &server{
db: db,
api: api,
done: make(chan int),
2023-09-18 23:57:18 +00:00
}
}
// Start server
func (s *server) Start() {
log.Info("Starting server...")
s.wg.Add(2)
2023-09-18 23:57:18 +00:00
go func() {
defer s.wg.Done()
err := s.api.Start()
if err != nil && err != http.ErrServerClosed {
log.Error("Starting server failed: ", err)
}
}()
go func() {
defer s.wg.Done()
ticker := time.NewTicker(15 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.runScheduledTasks()
case <-s.done:
log.Info("Stopping task runner...")
return
}
2023-09-18 23:57:18 +00:00
}
}()
log.Info("Server started")
}
// Stop server
func (s *server) Stop() {
log.Info("Stopping server...")
if err := s.api.Stop(); err != nil {
log.Error("HTTP server stop failed: ", err)
}
close(s.done)
s.wg.Wait()
log.Info("Server stopped")
2023-09-18 23:57:18 +00:00
}
// Run normal scheduled tasks
func (s *server) runScheduledTasks() {
start := time.Now()
if err := s.db.CacheTempTables(); err != nil {
log.Warn("Refreshing temp table cache failed: ", err)
}
log.Debug("Completed in: ", time.Since(start))
}