forked from decred/dcrdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
58 lines (49 loc) · 1.34 KB
/
web.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
package main
import (
"bytes"
"html/template"
"io"
"net/http"
"path/filepath"
"github.com/dcrdata/dcrdata/blockdata"
apitypes "github.com/dcrdata/dcrdata/dcrdataapi"
)
func TemplateExecToString(t *template.Template, name string, data interface{}) (string, error) {
var page bytes.Buffer
err := t.ExecuteTemplate(&page, name, data)
return page.String(), err
}
type WebTemplateData struct {
BlockSummary apitypes.BlockDataBasic
StakeSummary apitypes.StakeInfoExtendedEstimates
}
type WebUI struct {
TemplateData WebTemplateData
templ *template.Template
}
func NewWebUI() *WebUI {
fp := filepath.Join("views", "root.tmpl")
tmpl, err := template.New("home").ParseFiles(fp)
if err != nil {
return nil
}
return &WebUI{
templ: tmpl,
}
}
func (td *WebUI) Store(blockData *blockdata.BlockData) error {
td.TemplateData.BlockSummary = blockData.ToBlockSummary()
td.TemplateData.StakeSummary = blockData.ToStakeInfoExtendedEstimates()
return nil
}
func (td *WebUI) RootPage(w http.ResponseWriter, r *http.Request) {
//err := td.templ.Execute(w, td.TemplateData)
str, err := TemplateExecToString(td.templ, "home", td.TemplateData)
if err != nil {
http.Error(w, "template execute failure", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}