/
base64.go
58 lines (48 loc) · 967 Bytes
/
base64.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 funcs
import (
"sync"
"github.com/hairyhenderson/gomplate/base64"
"github.com/hairyhenderson/gomplate/conv"
)
var (
bf *Base64Funcs
bfInit sync.Once
)
// Base64NS - the base64 namespace
func Base64NS() *Base64Funcs {
bfInit.Do(func() { bf = &Base64Funcs{} })
return bf
}
// AddBase64Funcs -
func AddBase64Funcs(f map[string]interface{}) {
f["base64"] = Base64NS
}
// Base64Funcs -
type Base64Funcs struct{}
// Encode -
func (f *Base64Funcs) Encode(in interface{}) string {
b := toBytes(in)
return base64.Encode(b)
}
// Decode -
func (f *Base64Funcs) Decode(in interface{}) string {
return string(base64.Decode(conv.ToString(in)))
}
type byter interface {
Bytes() []byte
}
func toBytes(in interface{}) []byte {
if in == nil {
return []byte{}
}
if s, ok := in.([]byte); ok {
return s
}
if s, ok := in.(byter); ok {
return s.Bytes()
}
if s, ok := in.(string); ok {
return []byte(s)
}
return []byte(conv.ToString(in))
}