-
Notifications
You must be signed in to change notification settings - Fork 0
/
store_template.go
52 lines (44 loc) · 1011 Bytes
/
store_template.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
package tracker
import (
"fmt"
"html/template"
"io"
"sync"
)
type TemplateID int
const (
TemplateIndex = iota
TemplateTorrent
)
type Templater interface {
// Add template to cache.
Add(ID TemplateID, template *template.Template)
// Execute template from cache using data.
Execute(ID TemplateID, wr io.Writer, data any) error
}
type templateStore struct {
mu *sync.RWMutex
templates map[TemplateID]*template.Template
}
// Create new template store.
func NewTemplateStore() *templateStore {
return &templateStore{
mu: &sync.RWMutex{},
templates: make(map[TemplateID]*template.Template),
}
}
func (c *templateStore) Add(ID TemplateID, template *template.Template) {
c.mu.Lock()
c.templates[ID] = template
c.mu.Unlock()
}
func (c *templateStore) Execute(ID TemplateID, wr io.Writer, data any) error {
c.mu.RLock()
tpl, ok := c.templates[ID]
c.mu.RUnlock()
if !ok {
return fmt.Errorf("template %q does not exist in cache", ID)
}
tpl.Execute(wr, data)
return nil
}