tpl: Unexport all template funcs

There is no good reason to export all the template funcs:

* They're not used outside the templates.
* If usable in other packages, they should be moved (to helpers?)
* They create too broad an interface;
  users of the tpl package don't see the forest for all the trees.
This commit is contained in:
Bjørn Erik Pedersen 2016-02-06 15:53:39 +01:00
parent d1d7702c06
commit 5995eaaa08
2 changed files with 213 additions and 214 deletions

View file

@ -38,8 +38,8 @@ import (
var funcMap template.FuncMap var funcMap template.FuncMap
// Eq returns the boolean truth of arg1 == arg2. // eq returns the boolean truth of arg1 == arg2.
func Eq(x, y interface{}) bool { func eq(x, y interface{}) bool {
normalize := func(v interface{}) interface{} { normalize := func(v interface{}) interface{} {
vv := reflect.ValueOf(v) vv := reflect.ValueOf(v)
switch vv.Kind() { switch vv.Kind() {
@ -58,39 +58,39 @@ func Eq(x, y interface{}) bool {
return reflect.DeepEqual(x, y) return reflect.DeepEqual(x, y)
} }
// Ne returns the boolean truth of arg1 != arg2. // ne returns the boolean truth of arg1 != arg2.
func Ne(x, y interface{}) bool { func ne(x, y interface{}) bool {
return !Eq(x, y) return !eq(x, y)
} }
// Ge returns the boolean truth of arg1 >= arg2. // ge returns the boolean truth of arg1 >= arg2.
func Ge(a, b interface{}) bool { func ge(a, b interface{}) bool {
left, right := compareGetFloat(a, b) left, right := compareGetFloat(a, b)
return left >= right return left >= right
} }
// Gt returns the boolean truth of arg1 > arg2. // gt returns the boolean truth of arg1 > arg2.
func Gt(a, b interface{}) bool { func gt(a, b interface{}) bool {
left, right := compareGetFloat(a, b) left, right := compareGetFloat(a, b)
return left > right return left > right
} }
// Le returns the boolean truth of arg1 <= arg2. // le returns the boolean truth of arg1 <= arg2.
func Le(a, b interface{}) bool { func le(a, b interface{}) bool {
left, right := compareGetFloat(a, b) left, right := compareGetFloat(a, b)
return left <= right return left <= right
} }
// Lt returns the boolean truth of arg1 < arg2. // lt returns the boolean truth of arg1 < arg2.
func Lt(a, b interface{}) bool { func lt(a, b interface{}) bool {
left, right := compareGetFloat(a, b) left, right := compareGetFloat(a, b)
return left < right return left < right
} }
// Dictionary creates a map[string]interface{} from the given parameters by // dictionary creates a map[string]interface{} from the given parameters by
// walking the parameters and treating them as key-value pairs. The number // walking the parameters and treating them as key-value pairs. The number
// of parameters must be even. // of parameters must be even.
func Dictionary(values ...interface{}) (map[string]interface{}, error) { func dictionary(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 { if len(values)%2 != 0 {
return nil, errors.New("invalid dict call") return nil, errors.New("invalid dict call")
} }
@ -167,10 +167,10 @@ func compareGetFloat(a interface{}, b interface{}) (float64, float64) {
return left, right return left, right
} }
// Slicestr slices a string by specifying a half-open range with // slicestr slices a string by specifying a half-open range with
// two indices, start and end. 1 and 4 creates a slice including elements 1 through 3. // two indices, start and end. 1 and 4 creates a slice including elements 1 through 3.
// The end index can be omitted, it defaults to the string's length. // The end index can be omitted, it defaults to the string's length.
func Slicestr(a interface{}, startEnd ...interface{}) (string, error) { func slicestr(a interface{}, startEnd ...interface{}) (string, error) {
aStr, err := cast.ToStringE(a) aStr, err := cast.ToStringE(a)
if err != nil { if err != nil {
return "", err return "", err
@ -214,7 +214,7 @@ func Slicestr(a interface{}, startEnd ...interface{}) (string, error) {
} }
// Substr extracts parts of a string, beginning at the character at the specified // substr extracts parts of a string, beginning at the character at the specified
// position, and returns the specified number of characters. // position, and returns the specified number of characters.
// //
// It normally takes two parameters: start and length. // It normally takes two parameters: start and length.
@ -226,7 +226,7 @@ func Slicestr(a interface{}, startEnd ...interface{}) (string, error) {
// In addition, borrowing from the extended behavior described at http://php.net/substr, // In addition, borrowing from the extended behavior described at http://php.net/substr,
// if length is given and is negative, then that many characters will be omitted from // if length is given and is negative, then that many characters will be omitted from
// the end of string. // the end of string.
func Substr(a interface{}, nums ...interface{}) (string, error) { func substr(a interface{}, nums ...interface{}) (string, error) {
aStr, err := cast.ToStringE(a) aStr, err := cast.ToStringE(a)
if err != nil { if err != nil {
return "", err return "", err
@ -287,8 +287,8 @@ func Substr(a interface{}, nums ...interface{}) (string, error) {
return string(asRunes[s:e]), nil return string(asRunes[s:e]), nil
} }
// Split slices an input string into all substrings separated by delimiter. // split slices an input string into all substrings separated by delimiter.
func Split(a interface{}, delimiter string) ([]string, error) { func split(a interface{}, delimiter string) ([]string, error) {
aStr, err := cast.ToStringE(a) aStr, err := cast.ToStringE(a)
if err != nil { if err != nil {
return []string{}, err return []string{}, err
@ -296,9 +296,9 @@ func Split(a interface{}, delimiter string) ([]string, error) {
return strings.Split(aStr, delimiter), nil return strings.Split(aStr, delimiter), nil
} }
// Intersect returns the common elements in the given sets, l1 and l2. l1 and // intersect returns the common elements in the given sets, l1 and l2. l1 and
// l2 must be of the same type and may be either arrays or slices. // l2 must be of the same type and may be either arrays or slices.
func Intersect(l1, l2 interface{}) (interface{}, error) { func intersect(l1, l2 interface{}) (interface{}, error) {
if l1 == nil || l2 == nil { if l1 == nil || l2 == nil {
return make([]interface{}, 0), nil return make([]interface{}, 0), nil
} }
@ -317,20 +317,20 @@ func Intersect(l1, l2 interface{}) (interface{}, error) {
l2vv := l2v.Index(j) l2vv := l2v.Index(j)
switch l1vv.Kind() { switch l1vv.Kind() {
case reflect.String: case reflect.String:
if l1vv.Type() == l2vv.Type() && l1vv.String() == l2vv.String() && !In(r, l2vv) { if l1vv.Type() == l2vv.Type() && l1vv.String() == l2vv.String() && !in(r, l2vv) {
r = reflect.Append(r, l2vv) r = reflect.Append(r, l2vv)
} }
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch l2vv.Kind() { switch l2vv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if l1vv.Int() == l2vv.Int() && !In(r, l2vv) { if l1vv.Int() == l2vv.Int() && !in(r, l2vv) {
r = reflect.Append(r, l2vv) r = reflect.Append(r, l2vv)
} }
} }
case reflect.Float32, reflect.Float64: case reflect.Float32, reflect.Float64:
switch l2vv.Kind() { switch l2vv.Kind() {
case reflect.Float32, reflect.Float64: case reflect.Float32, reflect.Float64:
if l1vv.Float() == l2vv.Float() && !In(r, l2vv) { if l1vv.Float() == l2vv.Float() && !in(r, l2vv) {
r = reflect.Append(r, l2vv) r = reflect.Append(r, l2vv)
} }
} }
@ -346,8 +346,8 @@ func Intersect(l1, l2 interface{}) (interface{}, error) {
} }
} }
// In returns whether v is in the set l. l may be an array or slice. // in returns whether v is in the set l. l may be an array or slice.
func In(l interface{}, v interface{}) bool { func in(l interface{}, v interface{}) bool {
lv := reflect.ValueOf(l) lv := reflect.ValueOf(l)
vv := reflect.ValueOf(v) vv := reflect.ValueOf(v)
@ -401,8 +401,8 @@ func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
return v, false return v, false
} }
// First returns the first N items in a rangeable list. // first returns the first N items in a rangeable list.
func First(limit interface{}, seq interface{}) (interface{}, error) { func first(limit interface{}, seq interface{}) (interface{}, error) {
if limit == nil || seq == nil { if limit == nil || seq == nil {
return nil, errors.New("both limit and seq must be provided") return nil, errors.New("both limit and seq must be provided")
} }
@ -435,8 +435,8 @@ func First(limit interface{}, seq interface{}) (interface{}, error) {
return seqv.Slice(0, limitv).Interface(), nil return seqv.Slice(0, limitv).Interface(), nil
} }
// Last returns the last N items in a rangeable list. // last returns the last N items in a rangeable list.
func Last(limit interface{}, seq interface{}) (interface{}, error) { func last(limit interface{}, seq interface{}) (interface{}, error) {
if limit == nil || seq == nil { if limit == nil || seq == nil {
return nil, errors.New("both limit and seq must be provided") return nil, errors.New("both limit and seq must be provided")
} }
@ -469,8 +469,8 @@ func Last(limit interface{}, seq interface{}) (interface{}, error) {
return seqv.Slice(seqv.Len()-limitv, seqv.Len()).Interface(), nil return seqv.Slice(seqv.Len()-limitv, seqv.Len()).Interface(), nil
} }
// After returns all the items after the first N in a rangeable list. // after returns all the items after the first N in a rangeable list.
func After(index interface{}, seq interface{}) (interface{}, error) { func after(index interface{}, seq interface{}) (interface{}, error) {
if index == nil || seq == nil { if index == nil || seq == nil {
return nil, errors.New("both limit and seq must be provided") return nil, errors.New("both limit and seq must be provided")
} }
@ -503,8 +503,8 @@ func After(index interface{}, seq interface{}) (interface{}, error) {
return seqv.Slice(indexv, seqv.Len()).Interface(), nil return seqv.Slice(indexv, seqv.Len()).Interface(), nil
} }
// Shuffle returns the given rangeable list in a randomised order. // shuffle returns the given rangeable list in a randomised order.
func Shuffle(seq interface{}) (interface{}, error) { func shuffle(seq interface{}) (interface{}, error) {
if seq == nil { if seq == nil {
return nil, errors.New("both count and seq must be provided") return nil, errors.New("both count and seq must be provided")
} }
@ -735,12 +735,12 @@ func checkCondition(v, mv reflect.Value, op string) (bool, error) {
case "in", "not in": case "in", "not in":
var r bool var r bool
if ivp != nil && len(ima) > 0 { if ivp != nil && len(ima) > 0 {
r = In(ima, *ivp) r = in(ima, *ivp)
} else if svp != nil { } else if svp != nil {
if len(sma) > 0 { if len(sma) > 0 {
r = In(sma, *svp) r = in(sma, *svp)
} else if smvp != nil { } else if smvp != nil {
r = In(*smvp, *svp) r = in(*smvp, *svp)
} }
} else { } else {
return false, nil return false, nil
@ -755,8 +755,8 @@ func checkCondition(v, mv reflect.Value, op string) (bool, error) {
return false, nil return false, nil
} }
// Where returns a filtered subset of a given data type. // where returns a filtered subset of a given data type.
func Where(seq, key interface{}, args ...interface{}) (r interface{}, err error) { func where(seq, key interface{}, args ...interface{}) (r interface{}, err error) {
seqv := reflect.ValueOf(seq) seqv := reflect.ValueOf(seq)
kv := reflect.ValueOf(key) kv := reflect.ValueOf(key)
@ -818,8 +818,8 @@ func Where(seq, key interface{}, args ...interface{}) (r interface{}, err error)
} }
} }
// Apply takes a map, array, or slice and returns a new slice with the function fname applied over it. // apply takes a map, array, or slice and returns a new slice with the function fname applied over it.
func Apply(seq interface{}, fname string, args ...interface{}) (interface{}, error) { func apply(seq interface{}, fname string, args ...interface{}) (interface{}, error) {
if seq == nil { if seq == nil {
return make([]interface{}, 0), nil return make([]interface{}, 0), nil
} }
@ -899,9 +899,9 @@ func applyFnToThis(fn, this reflect.Value, args ...interface{}) (reflect.Value,
return reflect.ValueOf(nil), res[1].Interface().(error) return reflect.ValueOf(nil), res[1].Interface().(error)
} }
// Delimit takes a given sequence and returns a delimited HTML string. // delimit takes a given sequence and returns a delimited HTML string.
// If last is passed to the function, it will be used as the final delimiter. // If last is passed to the function, it will be used as the final delimiter.
func Delimit(seq, delimiter interface{}, last ...interface{}) (template.HTML, error) { func delimit(seq, delimiter interface{}, last ...interface{}) (template.HTML, error) {
d, err := cast.ToStringE(delimiter) d, err := cast.ToStringE(delimiter)
if err != nil { if err != nil {
return "", err return "", err
@ -926,7 +926,7 @@ func Delimit(seq, delimiter interface{}, last ...interface{}) (template.HTML, er
var str string var str string
switch seqv.Kind() { switch seqv.Kind() {
case reflect.Map: case reflect.Map:
sortSeq, err := Sort(seq) sortSeq, err := sortSeq(seq)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -956,8 +956,8 @@ func Delimit(seq, delimiter interface{}, last ...interface{}) (template.HTML, er
return template.HTML(str), nil return template.HTML(str), nil
} }
// Sort returns a sorted sequence. // sortSeq returns a sorted sequence.
func Sort(seq interface{}, args ...interface{}) (interface{}, error) { func sortSeq(seq interface{}, args ...interface{}) (interface{}, error) {
seqv := reflect.ValueOf(seq) seqv := reflect.ValueOf(seq)
seqv, isNil := indirect(seqv) seqv, isNil := indirect(seqv)
if isNil { if isNil {
@ -1055,7 +1055,7 @@ type pairList struct {
func (p pairList) Swap(i, j int) { p.Pairs[i], p.Pairs[j] = p.Pairs[j], p.Pairs[i] } func (p pairList) Swap(i, j int) { p.Pairs[i], p.Pairs[j] = p.Pairs[j], p.Pairs[i] }
func (p pairList) Len() int { return len(p.Pairs) } func (p pairList) Len() int { return len(p.Pairs) }
func (p pairList) Less(i, j int) bool { func (p pairList) Less(i, j int) bool {
return Lt(p.Pairs[i].SortByValue.Interface(), p.Pairs[j].SortByValue.Interface()) return lt(p.Pairs[i].SortByValue.Interface(), p.Pairs[j].SortByValue.Interface())
} }
// sorts a pairList and returns a slice of sorted values // sorts a pairList and returns a slice of sorted values
@ -1073,9 +1073,9 @@ func (p pairList) sort() interface{} {
return sorted.Interface() return sorted.Interface()
} }
// IsSet returns whether a given array, channel, slice, or map has a key // isSet returns whether a given array, channel, slice, or map has a key
// defined. // defined.
func IsSet(a interface{}, key interface{}) bool { func isSet(a interface{}, key interface{}) bool {
av := reflect.ValueOf(a) av := reflect.ValueOf(a)
kv := reflect.ValueOf(key) kv := reflect.ValueOf(key)
@ -1093,9 +1093,9 @@ func IsSet(a interface{}, key interface{}) bool {
return false return false
} }
// ReturnWhenSet returns a given value if it set. Otherwise, it returns an // returnWhenSet returns a given value if it set. Otherwise, it returns an
// empty string. // empty string.
func ReturnWhenSet(a, k interface{}) interface{} { func returnWhenSet(a, k interface{}) interface{} {
av, isNil := indirect(reflect.ValueOf(a)) av, isNil := indirect(reflect.ValueOf(a))
if isNil { if isNil {
return "" return ""
@ -1131,8 +1131,8 @@ func ReturnWhenSet(a, k interface{}) interface{} {
return "" return ""
} }
// Highlight returns an HTML string with syntax highlighting applied. // highlight returns an HTML string with syntax highlighting applied.
func Highlight(in interface{}, lang, opts string) template.HTML { func highlight(in interface{}, lang, opts string) template.HTML {
var str string var str string
av := reflect.ValueOf(in) av := reflect.ValueOf(in)
switch av.Kind() { switch av.Kind() {
@ -1146,8 +1146,8 @@ func Highlight(in interface{}, lang, opts string) template.HTML {
var markdownTrimPrefix = []byte("<p>") var markdownTrimPrefix = []byte("<p>")
var markdownTrimSuffix = []byte("</p>\n") var markdownTrimSuffix = []byte("</p>\n")
// Markdownify renders a given string from Markdown to HTML. // markdownify renders a given string from Markdown to HTML.
func Markdownify(text string) template.HTML { func markdownify(text string) template.HTML {
m := helpers.RenderBytes(&helpers.RenderingContext{Content: []byte(text), PageFmt: "markdown"}) m := helpers.RenderBytes(&helpers.RenderingContext{Content: []byte(text), PageFmt: "markdown"})
m = bytes.TrimPrefix(m, markdownTrimPrefix) m = bytes.TrimPrefix(m, markdownTrimPrefix)
m = bytes.TrimSuffix(m, markdownTrimSuffix) m = bytes.TrimSuffix(m, markdownTrimSuffix)
@ -1181,18 +1181,18 @@ func refPage(page interface{}, ref, methodName string) template.HTML {
return template.HTML(ref) return template.HTML(ref)
} }
// Ref returns the absolute URL path to a given content item. // ref returns the absolute URL path to a given content item.
func Ref(page interface{}, ref string) template.HTML { func ref(page interface{}, ref string) template.HTML {
return refPage(page, ref, "Ref") return refPage(page, ref, "Ref")
} }
// RelRef returns the relative URL path to a given content item. // relRef returns the relative URL path to a given content item.
func RelRef(page interface{}, ref string) template.HTML { func relRef(page interface{}, ref string) template.HTML {
return refPage(page, ref, "RelRef") return refPage(page, ref, "RelRef")
} }
// Chomp removes trailing newline characters from a string. // chomp removes trailing newline characters from a string.
func Chomp(text interface{}) (string, error) { func chomp(text interface{}) (string, error) {
s, err := cast.ToStringE(text) s, err := cast.ToStringE(text)
if err != nil { if err != nil {
return "", err return "", err
@ -1201,8 +1201,8 @@ func Chomp(text interface{}) (string, error) {
return strings.TrimRight(s, "\r\n"), nil return strings.TrimRight(s, "\r\n"), nil
} }
// Trim leading/trailing characters defined by b from a // trim leading/trailing characters defined by b from a
func Trim(a interface{}, b string) (string, error) { func trim(a interface{}, b string) (string, error) {
aStr, err := cast.ToStringE(a) aStr, err := cast.ToStringE(a)
if err != nil { if err != nil {
return "", err return "", err
@ -1210,8 +1210,8 @@ func Trim(a interface{}, b string) (string, error) {
return strings.Trim(aStr, b), nil return strings.Trim(aStr, b), nil
} }
// Replace all occurences of b with c in a // replace all occurences of b with c in a
func Replace(a, b, c interface{}) (string, error) { func replace(a, b, c interface{}) (string, error) {
aStr, err := cast.ToStringE(a) aStr, err := cast.ToStringE(a)
if err != nil { if err != nil {
return "", err return "", err
@ -1227,10 +1227,10 @@ func Replace(a, b, c interface{}) (string, error) {
return strings.Replace(aStr, bStr, cStr, -1), nil return strings.Replace(aStr, bStr, cStr, -1), nil
} }
// DateFormat converts the textual representation of the datetime string into // dateFormat converts the textual representation of the datetime string into
// the other form or returns it of the time.Time value. These are formatted // the other form or returns it of the time.Time value. These are formatted
// with the layout string // with the layout string
func DateFormat(layout string, v interface{}) (string, error) { func dateFormat(layout string, v interface{}) (string, error) {
t, err := cast.ToTimeE(v) t, err := cast.ToTimeE(v)
if err != nil { if err != nil {
return "", err return "", err
@ -1238,29 +1238,29 @@ func DateFormat(layout string, v interface{}) (string, error) {
return t.Format(layout), nil return t.Format(layout), nil
} }
// SafeHTMLAttr returns a given string as html/template HTMLAttr content. // safeHTMLAttr returns a given string as html/template HTMLAttr content.
// //
// SafeHTMLAttr is currently disabled, pending further discussion // safeHTMLAttr is currently disabled, pending further discussion
// on its use case. 2015-01-19 // on its use case. 2015-01-19
func SafeHTMLAttr(text string) template.HTMLAttr { func safeHTMLAttr(text string) template.HTMLAttr {
return template.HTMLAttr(text) return template.HTMLAttr(text)
} }
// SafeCSS returns a given string as html/template CSS content. // safeCSS returns a given string as html/template CSS content.
func SafeCSS(text string) template.CSS { func safeCSS(text string) template.CSS {
return template.CSS(text) return template.CSS(text)
} }
// SafeURL returns a given string as html/template URL content. // safeURL returns a given string as html/template URL content.
func SafeURL(text string) template.URL { func safeURL(text string) template.URL {
return template.URL(text) return template.URL(text)
} }
// SafeHTML returns a given string as html/template HTML content. // safeHTML returns a given string as html/template HTML content.
func SafeHTML(a string) template.HTML { return template.HTML(a) } func safeHTML(a string) template.HTML { return template.HTML(a) }
// SafeJS returns the given string as a html/template JS content. // safeJS returns the given string as a html/template JS content.
func SafeJS(a string) template.JS { return template.JS(a) } func safeJS(a string) template.JS { return template.JS(a) }
func doArithmetic(a, b interface{}, op rune) (interface{}, error) { func doArithmetic(a, b interface{}, op rune) (interface{}, error) {
av := reflect.ValueOf(a) av := reflect.ValueOf(a)
@ -1376,8 +1376,8 @@ func doArithmetic(a, b interface{}, op rune) (interface{}, error) {
} }
} }
// Mod returns a % b. // mod returns a % b.
func Mod(a, b interface{}) (int64, error) { func mod(a, b interface{}) (int64, error) {
av := reflect.ValueOf(a) av := reflect.ValueOf(a)
bv := reflect.ValueOf(b) bv := reflect.ValueOf(b)
var ai, bi int64 var ai, bi int64
@ -1403,17 +1403,17 @@ func Mod(a, b interface{}) (int64, error) {
return ai % bi, nil return ai % bi, nil
} }
// ModBool returns the boolean of a % b. If a % b == 0, return true. // modBool returns the boolean of a % b. If a % b == 0, return true.
func ModBool(a, b interface{}) (bool, error) { func modBool(a, b interface{}) (bool, error) {
res, err := Mod(a, b) res, err := mod(a, b)
if err != nil { if err != nil {
return false, err return false, err
} }
return res == int64(0), nil return res == int64(0), nil
} }
// Base64Decode returns the base64 decoding of the given content. // base64Decode returns the base64 decoding of the given content.
func Base64Decode(content interface{}) (string, error) { func base64Decode(content interface{}) (string, error) {
conv, err := cast.ToStringE(content) conv, err := cast.ToStringE(content)
if err != nil { if err != nil {
@ -1429,8 +1429,8 @@ func Base64Decode(content interface{}) (string, error) {
return string(dec), nil return string(dec), nil
} }
// Base64Encode returns the base64 encoding of the given content. // base64Encode returns the base64 encoding of the given content.
func Base64Encode(content interface{}) (string, error) { func base64Encode(content interface{}) (string, error) {
conv, err := cast.ToStringE(content) conv, err := cast.ToStringE(content)
if err != nil { if err != nil {
@ -1440,8 +1440,8 @@ func Base64Encode(content interface{}) (string, error) {
return base64.StdEncoding.EncodeToString([]byte(conv)), nil return base64.StdEncoding.EncodeToString([]byte(conv)), nil
} }
// CountWords returns the approximate word count of the given content. // countWords returns the approximate word count of the given content.
func CountWords(content interface{}) (int, error) { func countWords(content interface{}) (int, error) {
conv, err := cast.ToStringE(content) conv, err := cast.ToStringE(content)
if err != nil { if err != nil {
@ -1461,8 +1461,8 @@ func CountWords(content interface{}) (int, error) {
return counter, nil return counter, nil
} }
// CountRunes returns the approximate rune count of the given content. // countRunes returns the approximate rune count of the given content.
func CountRunes(content interface{}) (int, error) { func countRunes(content interface{}) (int, error) {
conv, err := cast.ToStringE(content) conv, err := cast.ToStringE(content)
if err != nil { if err != nil {
@ -1479,9 +1479,9 @@ func CountRunes(content interface{}) (int, error) {
return counter, nil return counter, nil
} }
// Humanize returns the humanized form of a single word. // humanize returns the humanized form of a single word.
// Example: "my-first-post" -> "My first post" // Example: "my-first-post" -> "My first post"
func Humanize(in interface{}) (string, error) { func humanize(in interface{}) (string, error) {
word, err := cast.ToStringE(in) word, err := cast.ToStringE(in)
if err != nil { if err != nil {
return "", err return "", err
@ -1489,8 +1489,8 @@ func Humanize(in interface{}) (string, error) {
return inflect.Humanize(word), nil return inflect.Humanize(word), nil
} }
// Pluralize returns the plural form of a single word. // pluralize returns the plural form of a single word.
func Pluralize(in interface{}) (string, error) { func pluralize(in interface{}) (string, error) {
word, err := cast.ToStringE(in) word, err := cast.ToStringE(in)
if err != nil { if err != nil {
return "", err return "", err
@ -1498,8 +1498,8 @@ func Pluralize(in interface{}) (string, error) {
return inflect.Pluralize(word), nil return inflect.Pluralize(word), nil
} }
// Singularize returns the singular form of a single word. // singularize returns the singular form of a single word.
func Singularize(in interface{}) (string, error) { func singularize(in interface{}) (string, error) {
word, err := cast.ToStringE(in) word, err := cast.ToStringE(in)
if err != nil { if err != nil {
return "", err return "", err
@ -1511,68 +1511,68 @@ func init() {
funcMap = template.FuncMap{ funcMap = template.FuncMap{
"absURL": func(a string) template.HTML { return template.HTML(helpers.AbsURL(a)) }, "absURL": func(a string) template.HTML { return template.HTML(helpers.AbsURL(a)) },
"add": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '+') }, "add": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '+') },
"after": After, "after": after,
"apply": Apply, "apply": apply,
"base64Decode": Base64Decode, "base64Decode": base64Decode,
"base64Encode": Base64Encode, "base64Encode": base64Encode,
"chomp": Chomp, "chomp": chomp,
"countrunes": CountRunes, "countrunes": countRunes,
"countwords": CountWords, "countwords": countWords,
"dateFormat": DateFormat, "dateFormat": dateFormat,
"delimit": Delimit, "delimit": delimit,
"dict": Dictionary, "dict": dictionary,
"div": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '/') }, "div": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '/') },
"echoParam": ReturnWhenSet, "echoParam": returnWhenSet,
"eq": Eq, "eq": eq,
"first": First, "first": first,
"ge": Ge, "ge": ge,
"getCSV": GetCSV, "getCSV": GetCSV,
"getJSON": GetJSON, "getJSON": GetJSON,
"getenv": func(varName string) string { return os.Getenv(varName) }, "getenv": func(varName string) string { return os.Getenv(varName) },
"gt": Gt, "gt": gt,
"hasPrefix": func(a, b string) bool { return strings.HasPrefix(a, b) }, "hasPrefix": func(a, b string) bool { return strings.HasPrefix(a, b) },
"highlight": Highlight, "highlight": highlight,
"humanize": Humanize, "humanize": humanize,
"in": In, "in": in,
"int": func(v interface{}) int { return cast.ToInt(v) }, "int": func(v interface{}) int { return cast.ToInt(v) },
"intersect": Intersect, "intersect": intersect,
"isSet": IsSet, "isSet": isSet,
"isset": IsSet, "isset": isSet,
"last": Last, "last": last,
"le": Le, "le": le,
"lower": func(a string) string { return strings.ToLower(a) }, "lower": func(a string) string { return strings.ToLower(a) },
"lt": Lt, "lt": lt,
"markdownify": Markdownify, "markdownify": markdownify,
"mod": Mod, "mod": mod,
"modBool": ModBool, "modBool": modBool,
"mul": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '*') }, "mul": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '*') },
"ne": Ne, "ne": ne,
"partial": Partial, "partial": Partial,
"pluralize": Pluralize, "pluralize": pluralize,
"readDir": ReadDir, "readDir": ReadDir,
"ref": Ref, "ref": ref,
"relURL": func(a string) template.HTML { return template.HTML(helpers.RelURL(a)) }, "relURL": func(a string) template.HTML { return template.HTML(helpers.RelURL(a)) },
"relref": RelRef, "relref": relRef,
"replace": Replace, "replace": replace,
"safeCSS": SafeCSS, "safeCSS": safeCSS,
"safeHTML": SafeHTML, "safeHTML": safeHTML,
"safeJS": SafeJS, "safeJS": safeJS,
"safeURL": SafeURL, "safeURL": safeURL,
"sanitizeURL": helpers.SanitizeURL, "sanitizeURL": helpers.SanitizeURL,
"sanitizeurl": helpers.SanitizeURL, "sanitizeurl": helpers.SanitizeURL,
"seq": helpers.Seq, "seq": helpers.Seq,
"shuffle": Shuffle, "shuffle": shuffle,
"singularize": Singularize, "singularize": singularize,
"slicestr": Slicestr, "slicestr": slicestr,
"sort": Sort, "sort": sortSeq,
"split": Split, "split": split,
"string": func(v interface{}) string { return cast.ToString(v) }, "string": func(v interface{}) string { return cast.ToString(v) },
"sub": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '-') }, "sub": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '-') },
"substr": Substr, "substr": substr,
"title": func(a string) string { return strings.Title(a) }, "title": func(a string) string { return strings.Title(a) },
"trim": Trim, "trim": trim,
"upper": func(a string) string { return strings.ToUpper(a) }, "upper": func(a string) string { return strings.ToUpper(a) },
"urlize": helpers.URLize, "urlize": helpers.URLize,
"where": Where, "where": where,
} }
} }

View file

@ -60,12 +60,12 @@ func TestCompare(t *testing.T) {
tstCompareType tstCompareType
funcUnderTest func(a, b interface{}) bool funcUnderTest func(a, b interface{}) bool
}{ }{
{tstGt, Gt}, {tstGt, gt},
{tstLt, Lt}, {tstLt, lt},
{tstGe, Ge}, {tstGe, ge},
{tstLe, Le}, {tstLe, le},
{tstEq, Eq}, {tstEq, eq},
{tstNe, Ne}, {tstNe, ne},
} { } {
doTestCompare(t, this.tstCompareType, this.funcUnderTest) doTestCompare(t, this.tstCompareType, this.funcUnderTest)
} }
@ -181,7 +181,7 @@ func TestMod(t *testing.T) {
{int32(3), int32(2), int64(1)}, {int32(3), int32(2), int64(1)},
{int64(3), int64(2), int64(1)}, {int64(3), int64(2), int64(1)},
} { } {
result, err := Mod(this.a, this.b) result, err := mod(this.a, this.b)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
t.Errorf("[%d] modulo didn't return an expected error", i) t.Errorf("[%d] modulo didn't return an expected error", i)
@ -221,7 +221,7 @@ func TestModBool(t *testing.T) {
{int64(3), int64(3), true}, {int64(3), int64(3), true},
{int64(3), int64(2), false}, {int64(3), int64(2), false},
} { } {
result, err := ModBool(this.a, this.b) result, err := modBool(this.a, this.b)
if this.expect == nil { if this.expect == nil {
if err == nil { if err == nil {
t.Errorf("[%d] modulo didn't return an expected error", i) t.Errorf("[%d] modulo didn't return an expected error", i)
@ -255,7 +255,7 @@ func TestFirst(t *testing.T) {
{nil, []int{100}, false}, {nil, []int{100}, false},
{1, t, false}, {1, t, false},
} { } {
results, err := First(this.count, this.sequence) results, err := first(this.count, this.sequence)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
t.Errorf("[%d] First didn't return an expected error", i) t.Errorf("[%d] First didn't return an expected error", i)
@ -289,7 +289,7 @@ func TestLast(t *testing.T) {
{nil, []int{100}, false}, {nil, []int{100}, false},
{1, t, false}, {1, t, false},
} { } {
results, err := Last(this.count, this.sequence) results, err := last(this.count, this.sequence)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
t.Errorf("[%d] First didn't return an expected error", i) t.Errorf("[%d] First didn't return an expected error", i)
@ -323,7 +323,7 @@ func TestAfter(t *testing.T) {
{nil, []int{100}, false}, {nil, []int{100}, false},
{1, t, false}, {1, t, false},
} { } {
results, err := After(this.count, this.sequence) results, err := after(this.count, this.sequence)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
t.Errorf("[%d] First didn't return an expected error", i) t.Errorf("[%d] First didn't return an expected error", i)
@ -356,7 +356,7 @@ func TestShuffleInputAndOutputFormat(t *testing.T) {
{nil, false}, {nil, false},
{t, false}, {t, false},
} { } {
results, err := Shuffle(this.sequence) results, err := shuffle(this.sequence)
if !this.success { if !this.success {
if err == nil { if err == nil {
t.Errorf("[%d] First didn't return an expected error", i) t.Errorf("[%d] First didn't return an expected error", i)
@ -389,7 +389,7 @@ func TestShuffleRandomising(t *testing.T) {
}{ }{
{rand.Perm(sequenceLength)}, {rand.Perm(sequenceLength)},
} { } {
results, _ := Shuffle(this.sequence) results, _ := shuffle(this.sequence)
resultsv := reflect.ValueOf(results) resultsv := reflect.ValueOf(results)
@ -415,7 +415,7 @@ func TestDictionary(t *testing.T) {
{[]interface{}{"a", 12, "b", []int{4}}, false, map[string]interface{}{"a": 12, "b": []int{4}}}, {[]interface{}{"a", 12, "b", []int{4}}, false, map[string]interface{}{"a": 12, "b": []int{4}}},
{[]interface{}{"a", "b", "c"}, true, nil}, {[]interface{}{"a", "b", "c"}, true, nil},
} { } {
r, e := Dictionary(this.v1...) r, e := dictionary(this.v1...)
if (this.expecterr && e == nil) || (!this.expecterr && e != nil) { if (this.expecterr && e == nil) || (!this.expecterr && e != nil) {
t.Errorf("[%d] got an unexpected error: %s", i, e) t.Errorf("[%d] got an unexpected error: %s", i, e)
@ -448,7 +448,7 @@ func TestIn(t *testing.T) {
{"this substring should be found", "substring", true}, {"this substring should be found", "substring", true},
{"this substring should not be found", "subseastring", false}, {"this substring should not be found", "subseastring", false},
} { } {
result := In(this.v1, this.v2) result := in(this.v1, this.v2)
if result != this.expect { if result != this.expect {
t.Errorf("[%d] got %v but expected %v", i, result, this.expect) t.Errorf("[%d] got %v but expected %v", i, result, this.expect)
@ -490,11 +490,11 @@ func TestSlicestr(t *testing.T) {
} { } {
var result string var result string
if this.v2 == nil { if this.v2 == nil {
result, err = Slicestr(this.v1) result, err = slicestr(this.v1)
} else if this.v3 == nil { } else if this.v3 == nil {
result, err = Slicestr(this.v1, this.v2) result, err = slicestr(this.v1, this.v2)
} else { } else {
result, err = Slicestr(this.v1, this.v2, this.v3) result, err = slicestr(this.v1, this.v2, this.v3)
} }
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
@ -554,9 +554,9 @@ func TestSubstr(t *testing.T) {
n = i n = i
if this.v3 == nil { if this.v3 == nil {
result, err = Substr(this.v1, this.v2) result, err = substr(this.v1, this.v2)
} else { } else {
result, err = Substr(this.v1, this.v2, this.v3) result, err = substr(this.v1, this.v2, this.v3)
} }
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
@ -575,13 +575,13 @@ func TestSubstr(t *testing.T) {
} }
n++ n++
_, err = Substr("abcdef") _, err = substr("abcdef")
if err == nil { if err == nil {
t.Errorf("[%d] Substr didn't return an expected error", n) t.Errorf("[%d] Substr didn't return an expected error", n)
} }
n++ n++
_, err = Substr("abcdef", 1, 2, 3) _, err = substr("abcdef", 1, 2, 3)
if err == nil { if err == nil {
t.Errorf("[%d] Substr didn't return an expected error", n) t.Errorf("[%d] Substr didn't return an expected error", n)
} }
@ -599,7 +599,7 @@ func TestSplit(t *testing.T) {
{123, "2", []string{"1", "3"}}, {123, "2", []string{"1", "3"}},
{tstNoStringer{}, ",", false}, {tstNoStringer{}, ",", false},
} { } {
result, err := Split(this.v1, this.v2) result, err := split(this.v1, this.v2)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
@ -637,7 +637,7 @@ func TestIntersect(t *testing.T) {
{[]int{1, 2, 4}, []int{3, 6}, []int{}}, {[]int{1, 2, 4}, []int{3, 6}, []int{}},
{[]float64{2.2, 4.4}, []float64{1.1, 2.2, 4.4}, []float64{2.2, 4.4}}, {[]float64{2.2, 4.4}, []float64{1.1, 2.2, 4.4}, []float64{2.2, 4.4}},
} { } {
results, err := Intersect(this.sequence1, this.sequence2) results, err := intersect(this.sequence1, this.sequence2)
if err != nil { if err != nil {
t.Errorf("[%d] failed: %s", i, err) t.Errorf("[%d] failed: %s", i, err)
continue continue
@ -647,13 +647,13 @@ func TestIntersect(t *testing.T) {
} }
} }
_, err1 := Intersect("not an array or slice", []string{"a"}) _, err1 := intersect("not an array or slice", []string{"a"})
if err1 == nil { if err1 == nil {
t.Error("Expected error for non array as first arg") t.Error("Expected error for non array as first arg")
} }
_, err2 := Intersect([]string{"a"}, "not an array or slice") _, err2 := intersect([]string{"a"}, "not an array or slice")
if err2 == nil { if err2 == nil {
t.Error("Expected error for non array as second arg") t.Error("Expected error for non array as second arg")
@ -664,10 +664,10 @@ func TestIsSet(t *testing.T) {
aSlice := []interface{}{1, 2, 3, 5} aSlice := []interface{}{1, 2, 3, 5}
aMap := map[string]interface{}{"a": 1, "b": 2} aMap := map[string]interface{}{"a": 1, "b": 2}
assert.True(t, IsSet(aSlice, 2)) assert.True(t, isSet(aSlice, 2))
assert.True(t, IsSet(aMap, "b")) assert.True(t, isSet(aMap, "b"))
assert.False(t, IsSet(aSlice, 22)) assert.False(t, isSet(aSlice, 22))
assert.False(t, IsSet(aMap, "bc")) assert.False(t, isSet(aMap, "bc"))
} }
func (x *TstX) TstRp() string { func (x *TstX) TstRp() string {
@ -1145,9 +1145,9 @@ func TestWhere(t *testing.T) {
var results interface{} var results interface{}
var err error var err error
if len(this.op) > 0 { if len(this.op) > 0 {
results, err = Where(this.sequence, this.key, this.op, this.match) results, err = where(this.sequence, this.key, this.op, this.match)
} else { } else {
results, err = Where(this.sequence, this.key, this.match) results, err = where(this.sequence, this.key, this.match)
} }
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
@ -1165,17 +1165,17 @@ func TestWhere(t *testing.T) {
} }
var err error var err error
_, err = Where(map[string]int{"a": 1, "b": 2}, "a", []byte("="), 1) _, err = where(map[string]int{"a": 1, "b": 2}, "a", []byte("="), 1)
if err == nil { if err == nil {
t.Errorf("Where called with none string op value didn't return an expected error") t.Errorf("Where called with none string op value didn't return an expected error")
} }
_, err = Where(map[string]int{"a": 1, "b": 2}, "a", []byte("="), 1, 2) _, err = where(map[string]int{"a": 1, "b": 2}, "a", []byte("="), 1, 2)
if err == nil { if err == nil {
t.Errorf("Where called with more than two variable arguments didn't return an expected error") t.Errorf("Where called with more than two variable arguments didn't return an expected error")
} }
_, err = Where(map[string]int{"a": 1, "b": 2}, "a") _, err = where(map[string]int{"a": 1, "b": 2}, "a")
if err == nil { if err == nil {
t.Errorf("Where called with no variable arguments didn't return an expected error") t.Errorf("Where called with no variable arguments didn't return an expected error")
} }
@ -1216,9 +1216,9 @@ func TestDelimit(t *testing.T) {
var result template.HTML var result template.HTML
var err error var err error
if this.last == nil { if this.last == nil {
result, err = Delimit(this.sequence, this.delimiter) result, err = delimit(this.sequence, this.delimiter)
} else { } else {
result, err = Delimit(this.sequence, this.delimiter, this.last) result, err = delimit(this.sequence, this.delimiter, this.last)
} }
if err != nil { if err != nil {
t.Errorf("[%d] failed: %s", i, err) t.Errorf("[%d] failed: %s", i, err)
@ -1405,9 +1405,9 @@ func TestSort(t *testing.T) {
var result interface{} var result interface{}
var err error var err error
if this.sortByField == nil { if this.sortByField == nil {
result, err = Sort(this.sequence) result, err = sortSeq(this.sequence)
} else { } else {
result, err = Sort(this.sequence, this.sortByField, this.sortAsc) result, err = sortSeq(this.sequence, this.sortByField, this.sortAsc)
} }
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
@ -1444,7 +1444,7 @@ func TestReturnWhenSet(t *testing.T) {
{map[string]TstX{"foo": {A: "a", B: "b"}, "bar": {A: "c", B: "d"}, "baz": {A: "e", B: "f"}}, "bar", ""}, {map[string]TstX{"foo": {A: "a", B: "b"}, "bar": {A: "c", B: "d"}, "baz": {A: "e", B: "f"}}, "bar", ""},
{(*[]string)(nil), "bar", ""}, {(*[]string)(nil), "bar", ""},
} { } {
result := ReturnWhenSet(this.data, this.key) result := returnWhenSet(this.data, this.key)
if !reflect.DeepEqual(result, this.expect) { if !reflect.DeepEqual(result, this.expect) {
t.Errorf("[%d] ReturnWhenSet got %v (type %v) but expected %v (type %v)", i, result, reflect.TypeOf(result), this.expect, reflect.TypeOf(this.expect)) t.Errorf("[%d] ReturnWhenSet got %v (type %v) but expected %v (type %v)", i, result, reflect.TypeOf(result), this.expect, reflect.TypeOf(this.expect))
} }
@ -1452,7 +1452,7 @@ func TestReturnWhenSet(t *testing.T) {
} }
func TestMarkdownify(t *testing.T) { func TestMarkdownify(t *testing.T) {
result := Markdownify("Hello **World!**") result := markdownify("Hello **World!**")
expect := template.HTML("Hello <strong>World!</strong>") expect := template.HTML("Hello <strong>World!</strong>")
@ -1465,37 +1465,37 @@ func TestApply(t *testing.T) {
strings := []interface{}{"a\n", "b\n"} strings := []interface{}{"a\n", "b\n"}
noStringers := []interface{}{tstNoStringer{}, tstNoStringer{}} noStringers := []interface{}{tstNoStringer{}, tstNoStringer{}}
chomped, _ := Apply(strings, "chomp", ".") chomped, _ := apply(strings, "chomp", ".")
assert.Equal(t, []interface{}{"a", "b"}, chomped) assert.Equal(t, []interface{}{"a", "b"}, chomped)
chomped, _ = Apply(strings, "chomp", "c\n") chomped, _ = apply(strings, "chomp", "c\n")
assert.Equal(t, []interface{}{"c", "c"}, chomped) assert.Equal(t, []interface{}{"c", "c"}, chomped)
chomped, _ = Apply(nil, "chomp", ".") chomped, _ = apply(nil, "chomp", ".")
assert.Equal(t, []interface{}{}, chomped) assert.Equal(t, []interface{}{}, chomped)
_, err := Apply(strings, "apply", ".") _, err := apply(strings, "apply", ".")
if err == nil { if err == nil {
t.Errorf("apply with apply should fail") t.Errorf("apply with apply should fail")
} }
var nilErr *error var nilErr *error
_, err = Apply(nilErr, "chomp", ".") _, err = apply(nilErr, "chomp", ".")
if err == nil { if err == nil {
t.Errorf("apply with nil in seq should fail") t.Errorf("apply with nil in seq should fail")
} }
_, err = Apply(strings, "dobedobedo", ".") _, err = apply(strings, "dobedobedo", ".")
if err == nil { if err == nil {
t.Errorf("apply with unknown func should fail") t.Errorf("apply with unknown func should fail")
} }
_, err = Apply(noStringers, "chomp", ".") _, err = apply(noStringers, "chomp", ".")
if err == nil { if err == nil {
t.Errorf("apply when func fails should fail") t.Errorf("apply when func fails should fail")
} }
_, err = Apply(tstNoStringer{}, "chomp", ".") _, err = apply(tstNoStringer{}, "chomp", ".")
if err == nil { if err == nil {
t.Errorf("apply with non-sequence should fail") t.Errorf("apply with non-sequence should fail")
} }
@ -1508,13 +1508,13 @@ func TestChomp(t *testing.T) {
"\r", "\r\r", "\r", "\r\r",
"\r\n", "\r\n\r\n", "\r\n", "\r\n\r\n",
} { } {
chomped, _ := Chomp(base + item) chomped, _ := chomp(base + item)
if chomped != base { if chomped != base {
t.Errorf("[%d] Chomp failed, got '%v'", i, chomped) t.Errorf("[%d] Chomp failed, got '%v'", i, chomped)
} }
_, err := Chomp(tstNoStringer{}) _, err := chomp(tstNoStringer{})
if err == nil { if err == nil {
t.Errorf("Chomp should fail") t.Errorf("Chomp should fail")
@ -1534,7 +1534,7 @@ func TestHumanize(t *testing.T) {
{tstNoStringer{}, false}, {tstNoStringer{}, false},
} { } {
result, err := Humanize(this.in) result, err := humanize(this.in)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
@ -1549,33 +1549,32 @@ func TestHumanize(t *testing.T) {
t.Errorf("[%d] Humanize got %v but expected %v", i, result, this.expect) t.Errorf("[%d] Humanize got %v but expected %v", i, result, this.expect)
} }
} }
} }
} }
func TestReplace(t *testing.T) { func TestReplace(t *testing.T) {
v, _ := Replace("aab", "a", "b") v, _ := replace("aab", "a", "b")
assert.Equal(t, "bbb", v) assert.Equal(t, "bbb", v)
v, _ = Replace("11a11", 1, 2) v, _ = replace("11a11", 1, 2)
assert.Equal(t, "22a22", v) assert.Equal(t, "22a22", v)
v, _ = Replace(12345, 1, 2) v, _ = replace(12345, 1, 2)
assert.Equal(t, "22345", v) assert.Equal(t, "22345", v)
_, e := Replace(tstNoStringer{}, "a", "b") _, e := replace(tstNoStringer{}, "a", "b")
assert.NotNil(t, e, "tstNoStringer isn't trimmable") assert.NotNil(t, e, "tstNoStringer isn't trimmable")
_, e = Replace("a", tstNoStringer{}, "b") _, e = replace("a", tstNoStringer{}, "b")
assert.NotNil(t, e, "tstNoStringer cannot be converted to string") assert.NotNil(t, e, "tstNoStringer cannot be converted to string")
_, e = Replace("a", "b", tstNoStringer{}) _, e = replace("a", "b", tstNoStringer{})
assert.NotNil(t, e, "tstNoStringer cannot be converted to string") assert.NotNil(t, e, "tstNoStringer cannot be converted to string")
} }
func TestTrim(t *testing.T) { func TestTrim(t *testing.T) {
v, _ := Trim("1234 my way 13", "123") v, _ := trim("1234 my way 13", "123")
assert.Equal(t, "4 my way ", v) assert.Equal(t, "4 my way ", v)
v, _ = Trim(" my way ", " ") v, _ = trim(" my way ", " ")
assert.Equal(t, "my way", v) assert.Equal(t, "my way", v)
v, _ = Trim(1234, "14") v, _ = trim(1234, "14")
assert.Equal(t, "23", v) assert.Equal(t, "23", v)
_, e := Trim(tstNoStringer{}, " ") _, e := trim(tstNoStringer{}, " ")
assert.NotNil(t, e, "tstNoStringer isn't trimmable") assert.NotNil(t, e, "tstNoStringer isn't trimmable")
} }
@ -1591,7 +1590,7 @@ func TestDateFormat(t *testing.T) {
{"Monday, Jan 2, 2006", 1421733600, false}, {"Monday, Jan 2, 2006", 1421733600, false},
{"Monday, Jan 2, 2006", 1421733600.123, false}, {"Monday, Jan 2, 2006", 1421733600.123, false},
} { } {
result, err := DateFormat(this.layout, this.value) result, err := dateFormat(this.layout, this.value)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {
t.Errorf("[%d] DateFormat didn't return an expected error", i) t.Errorf("[%d] DateFormat didn't return an expected error", i)
@ -1633,7 +1632,7 @@ func TestSafeHTML(t *testing.T) {
} }
buf.Reset() buf.Reset()
err = tmpl.Execute(buf, SafeHTML(this.str)) err = tmpl.Execute(buf, safeHTML(this.str))
if err != nil { if err != nil {
t.Errorf("[%d] execute template with an escaped string value by SafeHTML returns unexpected error: %s", i, err) t.Errorf("[%d] execute template with an escaped string value by SafeHTML returns unexpected error: %s", i, err)
} }
@ -1668,7 +1667,7 @@ func TestSafeHTMLAttr(t *testing.T) {
} }
buf.Reset() buf.Reset()
err = tmpl.Execute(buf, SafeHTMLAttr(this.str)) err = tmpl.Execute(buf, safeHTMLAttr(this.str))
if err != nil { if err != nil {
t.Errorf("[%d] execute template with an escaped string value by SafeHTMLAttr returns unexpected error: %s", i, err) t.Errorf("[%d] execute template with an escaped string value by SafeHTMLAttr returns unexpected error: %s", i, err)
} }
@ -1703,7 +1702,7 @@ func TestSafeCSS(t *testing.T) {
} }
buf.Reset() buf.Reset()
err = tmpl.Execute(buf, SafeCSS(this.str)) err = tmpl.Execute(buf, safeCSS(this.str))
if err != nil { if err != nil {
t.Errorf("[%d] execute template with an escaped string value by SafeCSS returns unexpected error: %s", i, err) t.Errorf("[%d] execute template with an escaped string value by SafeCSS returns unexpected error: %s", i, err)
} }
@ -1738,7 +1737,7 @@ func TestSafeJS(t *testing.T) {
} }
buf.Reset() buf.Reset()
err = tmpl.Execute(buf, SafeJS(this.str)) err = tmpl.Execute(buf, safeJS(this.str))
if err != nil { if err != nil {
t.Errorf("[%d] execute template with an escaped string value by SafeJS returns unexpected error: %s", i, err) t.Errorf("[%d] execute template with an escaped string value by SafeJS returns unexpected error: %s", i, err)
} }
@ -1773,7 +1772,7 @@ func TestSafeURL(t *testing.T) {
} }
buf.Reset() buf.Reset()
err = tmpl.Execute(buf, SafeURL(this.str)) err = tmpl.Execute(buf, safeURL(this.str))
if err != nil { if err != nil {
t.Errorf("[%d] execute template with an escaped string value by SafeURL returns unexpected error: %s", i, err) t.Errorf("[%d] execute template with an escaped string value by SafeURL returns unexpected error: %s", i, err)
} }
@ -1786,7 +1785,7 @@ func TestSafeURL(t *testing.T) {
func TestBase64Decode(t *testing.T) { func TestBase64Decode(t *testing.T) {
testStr := "abc123!?$*&()'-=@~" testStr := "abc123!?$*&()'-=@~"
enc := base64.StdEncoding.EncodeToString([]byte(testStr)) enc := base64.StdEncoding.EncodeToString([]byte(testStr))
result, err := Base64Decode(enc) result, err := base64Decode(enc)
if err != nil { if err != nil {
t.Error("Base64Decode:", err) t.Error("Base64Decode:", err)
@ -1805,7 +1804,7 @@ func TestBase64Encode(t *testing.T) {
t.Error("Base64Encode: the DecodeString function of the base64 package returned an error.", err) t.Error("Base64Encode: the DecodeString function of the base64 package returned an error.", err)
} }
result, err := Base64Encode(string(dec)) result, err := base64Encode(string(dec))
if err != nil { if err != nil {
t.Errorf("Base64Encode: Can't cast arg '%s' into a string.", testStr) t.Errorf("Base64Encode: Can't cast arg '%s' into a string.", testStr)