forked from vkuznet/MLHub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
86 lines (75 loc) · 1.74 KB
/
templates.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
package main
// templates module
//
// Copyright (c) 2023 - Valentin Kuznetsov <[email protected]>
//
import (
"bytes"
"fmt"
"html/template"
"log"
"strconv"
"time"
)
// TmplRecord represent template record
type TmplRecord map[string]interface{}
// GetString converts given value for provided key to string data-type
func (t TmplRecord) GetString(key string) string {
if v, ok := t[key]; ok {
return fmt.Sprintf("%v", v)
}
return ""
}
// GetInt converts given value for provided key to int data-type
func (t TmplRecord) GetInt(key string) int {
if v, ok := t[key]; ok {
if val, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
return val
} else {
log.Println("ERROR:", err)
}
}
return 0
}
// GetError returns error string
func (t TmplRecord) GetError() string {
if v, ok := t["Error"]; ok {
return fmt.Sprintf("%v", v)
}
return ""
}
// GetBytes returns bytes object for given key
func (t TmplRecord) GetBytes(key string) []byte {
if data, ok := t[key]; ok {
return data.([]byte)
}
return []byte{}
}
// GetElapsedTime returns elapsed time
func (t TmplRecord) GetElapsedTime() string {
if val, ok := t["StartTime"]; ok {
startTime := time.Unix(val.(int64), 0)
return time.Since(startTime).String()
}
return ""
}
// Templates structure
type Templates struct {
html string
}
// Tmpl method for ServerTemplates structure
func (q Templates) Tmpl(tfile string, tmplData map[string]interface{}) string {
if q.html != "" {
return q.html
}
// get template from embed.FS
filenames := []string{"static/templates/" + tfile}
t := template.Must(template.New(tfile).ParseFS(StaticFs, filenames...))
buf := new(bytes.Buffer)
err := t.Execute(buf, tmplData)
if err != nil {
panic(err)
}
q.html = buf.String()
return q.html
}