-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmlpage.go
117 lines (92 loc) · 2.3 KB
/
htmlpage.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package htmlpage
import (
"bytes"
"html/template"
"io"
"net/http"
"sync"
"github.com/alrusov/misc"
"github.com/alrusov/balance-collector/internal/config"
)
//----------------------------------------------------------------------------------------------------------------------------//
var (
mutex = new(sync.Mutex)
cache = map[string]*template.Template{}
cacheEnabled = false
)
//----------------------------------------------------------------------------------------------------------------------------//
// Do --
func Do(name string, w http.ResponseWriter, r *http.Request, errMsg string, title string, data interface{}) (err error) {
cfg := config.Get()
mutex.Lock()
locked := true
defer func() {
if locked {
mutex.Unlock()
}
}()
t, exists := cache[name]
if !exists {
fn := ""
fn, err = misc.AbsPath(cfg.Processor.TemplatesDir + "/" + name + ".tpl")
if err != nil {
return
}
t, err = template.ParseFiles(fn)
if err != nil {
return
}
fn, err = misc.AbsPath(cfg.Processor.TemplatesDir + "/snippets/*.tpl")
if err != nil {
return
}
t, err = t.ParseGlob(fn)
if err != nil {
return
}
if cacheEnabled {
cache[name] = t
}
}
t, err = t.Clone()
if err != nil {
return
}
mutex.Unlock()
locked = false
params := struct {
Base string
Error string
Title string
Copyright string
Name string
App string
Version string
Tags string
Data interface{}
}{
Base: r.URL.Path,
Error: errMsg,
Title: title,
Copyright: misc.Copyright(),
Name: cfg.Common.Name,
App: misc.AppName(),
Version: misc.AppVersion(),
Tags: misc.AppTags(),
Data: data,
}
buf := new(bytes.Buffer)
err = t.ExecuteTemplate(buf, name, params)
if err != nil {
return
}
w.WriteHeader(http.StatusOK)
_, err = io.Copy(w, buf)
return
}
//----------------------------------------------------------------------------------------------------------------------------//
// JSON --
func JSON(cfg *config.Config, w http.ResponseWriter, r *http.Request, errMsg string, title string, data string) (err error) {
return Do("json", w, r, errMsg, title, data)
}
//----------------------------------------------------------------------------------------------------------------------------//