github.com/wynshop-open-source/gomplate@v3.5.0+incompatible/funcs/base64.go (about)

     1  package funcs
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/hairyhenderson/gomplate/base64"
     7  	"github.com/hairyhenderson/gomplate/conv"
     8  )
     9  
    10  var (
    11  	bf     *Base64Funcs
    12  	bfInit sync.Once
    13  )
    14  
    15  // Base64NS - the base64 namespace
    16  func Base64NS() *Base64Funcs {
    17  	bfInit.Do(func() { bf = &Base64Funcs{} })
    18  	return bf
    19  }
    20  
    21  // AddBase64Funcs -
    22  func AddBase64Funcs(f map[string]interface{}) {
    23  	f["base64"] = Base64NS
    24  }
    25  
    26  // Base64Funcs -
    27  type Base64Funcs struct{}
    28  
    29  // Encode -
    30  func (f *Base64Funcs) Encode(in interface{}) (string, error) {
    31  	b := toBytes(in)
    32  	return base64.Encode(b)
    33  }
    34  
    35  // Decode -
    36  func (f *Base64Funcs) Decode(in interface{}) (string, error) {
    37  	out, err := base64.Decode(conv.ToString(in))
    38  	return string(out), err
    39  }
    40  
    41  type byter interface {
    42  	Bytes() []byte
    43  }
    44  
    45  func toBytes(in interface{}) []byte {
    46  	if in == nil {
    47  		return []byte{}
    48  	}
    49  	if s, ok := in.([]byte); ok {
    50  		return s
    51  	}
    52  	if s, ok := in.(byter); ok {
    53  		return s.Bytes()
    54  	}
    55  	if s, ok := in.(string); ok {
    56  		return []byte(s)
    57  	}
    58  	return []byte(conv.ToString(in))
    59  }