-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
67 lines (60 loc) · 1.42 KB
/
server.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
package tracker
import (
"context"
"html/template"
"os"
"path"
"time"
"github.com/go-playground/validator/v10"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/rs/zerolog/log"
)
type Server struct {
config *ServerConfig
validator *validator.Validate
pool *pgxpool.Pool
store TorrentStorable
templates Templater
}
func NewServer(config *ServerConfig) *Server {
pgxconfig, err := pgxpool.ParseConfig(config.DSN)
if err != nil {
log.Fatal().Err(err).Msg("unable to parse pgxpool config")
}
pgxpool, err := pgxpool.NewWithConfig(context.Background(), pgxconfig)
if err != nil {
log.Fatal().Err(err).Msg("unable to create pgxpool")
}
return &Server{
config: config,
validator: validator.New(),
pool: pgxpool,
store: NewTorrentStore(pgxpool),
templates: NewTemplateStore(),
}
}
// Creates a goroutine that runs function f every duration d.
// ts gives access to the store.
func (sv *Server) RunTask(d time.Duration, f func(ts TorrentStorable)) {
go func() {
for range time.Tick(d) {
f(sv.store)
}
}()
}
func (sv *Server) CacheTemplates() {
// index
tplIndex := template.Must(
template.ParseFiles(
path.Join(os.Getenv("TEMPLATE_PATH"), "index.html"),
),
)
sv.templates.Add(TemplateIndex, tplIndex)
// torrent
tplTorrent := template.Must(
template.ParseFiles(
path.Join(os.Getenv("TEMPLATE_PATH"), "torrent.html"),
),
)
sv.templates.Add(TemplateTorrent, tplTorrent)
}