This repository has been archived by the owner on May 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
95 lines (82 loc) · 2.2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"godash/bookmarks"
"godash/system"
"godash/weather"
"context"
"fmt"
"html/template"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/Masterminds/sprig/v3"
"github.com/caarlos0/env/v6"
"github.com/labstack/echo/v4"
"github.com/r3labs/sse/v2"
"go.uber.org/zap"
)
type goDash struct {
router *echo.Echo
logger *zap.SugaredLogger
sse *sse.Server
config config
info info
}
type info struct {
weather *weather.Weather
bookmarks *bookmarks.Config
system *system.System
}
type config struct {
Title string `env:"TITLE" envDefault:"goDash"`
Port int `env:"PORT" envDefault:"4000"`
AllowedHosts []string `env:"ALLOWED_HOSTS" envDefault:"*" envSeparator:","`
LogLevel string `env:"LOG_LEVEL" envDefault:"info"`
LiveSystem bool `env:"LIVE_SYSTEM" envDefault:"true"`
}
func (g *goDash) createInfoServices() {
g.sse.AutoReplay = false
g.sse.CreateStream("system")
g.sse.CreateStream("weather")
g.info = info{
weather: weather.NewWeatherService(g.logger, g.sse),
bookmarks: bookmarks.NewBookmarkService(g.logger),
system: system.NewSystemService(g.config.LiveSystem, g.logger, g.sse),
}
}
func (g *goDash) startServer() {
if err := g.router.Start(fmt.Sprintf(":%d", g.config.Port)); err != nil && err != http.ErrServerClosed {
g.logger.Fatal("shutting down the server")
}
}
func (g *goDash) setupTemplateRender() {
g.router.Renderer = &TemplateRenderer{
templates: template.Must(template.New("").Funcs(sprig.FuncMap()).ParseGlob("templates/*.html")),
}
}
func main() {
g := goDash{router: echo.New(), sse: sse.New()}
if err := env.Parse(&g.config); err != nil {
panic(err)
}
g.setupTemplateRender()
g.setupLogger()
defer g.logger.Sync()
g.setupEchoLogging()
g.setupMiddlewares()
g.createInfoServices()
g.setupRouter()
go g.startServer()
g.logger.Infof("running on %s:%d", "http://localhost", g.config.Port)
quit := make(chan os.Signal, 1)
// https://docs.docker.com/engine/reference/commandline/stop/
signal.Notify(quit, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := g.router.Shutdown(ctx); err != nil {
g.logger.Fatal(err)
}
}