summaryrefslogtreecommitdiff
path: root/funcs/base64.go
blob: ac7cf3ee972a272d82ec5b0f64ec6d2b4458da84 (plain)
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
package funcs

import (
	"sync"

	"github.com/hairyhenderson/gomplate/v3/base64"
	"github.com/hairyhenderson/gomplate/v3/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, error) {
	b := toBytes(in)
	return base64.Encode(b)
}

// Decode -
func (f *Base64Funcs) Decode(in interface{}) (string, error) {
	out, err := base64.Decode(conv.ToString(in))
	return string(out), err
}

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))
}