forked from subchen/frep
/
func.go
104 lines (94 loc) · 2.21 KB
/
func.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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"os"
"text/template"
"time"
"github.com/BurntSushi/toml"
"github.com/Masterminds/sprig"
"github.com/go-yaml/yaml"
)
func FuncMap() template.FuncMap {
f := sprig.TxtFuncMap()
// marshal
f["toJson"] = toJson
f["toYaml"] = toYaml
f["toToml"] = toToml
// file
f["fileSize"] = fileSize
f["fileLastModified"] = fileLastModified
f["fileGetBytes"] = fileGetBytes
f["fileGetString"] = fileGetString
return f
}
// toJson takes an interface, marshals it to json, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toJson(v interface{}) string {
data, err := json.Marshal(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return string(data)
}
// toYaml takes an interface, marshals it to yaml, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toYaml(v interface{}) string {
data, err := yaml.Marshal(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return string(data)
}
// toToml takes an interface, marshals it to toml, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toToml(v interface{}) string {
b := bytes.NewBuffer(nil)
e := toml.NewEncoder(b)
err := e.Encode(v)
if err != nil {
return err.Error()
}
return b.String()
}
func fileSize(file string) int64 {
info, err := os.Stat(file)
if err != nil {
// Swallow errors inside of a template.
return -1
}
return info.Size()
}
func fileLastModified(file string) time.Time {
info, err := os.Stat(file)
if err != nil {
// Swallow errors inside of a template.
return time.Unix(0, 0)
}
return info.ModTime()
}
func fileGetBytes(file string) []byte {
data, err := ioutil.ReadFile(file)
if err != nil {
// Swallow errors inside of a template.
return nil
}
return data
}
func fileGetString(file string) string {
data, err := ioutil.ReadFile(file)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return string(data)
}