tpl: Update hasPrefix to accept interface{} params
authorCameron Moore <moorereason@gmail.com>
Thu, 22 Dec 2016 23:29:31 +0000 (17:29 -0600)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 23 Dec 2016 08:51:03 +0000 (09:51 +0100)
Updates #2822

tpl/template_funcs.go
tpl/template_funcs_test.go

index 8f552637864b1b1bd570221e7137898e9259280b..4ed6a159fbd88aebd7ef61b1649c6ac8f0e5e379 100644 (file)
@@ -239,6 +239,21 @@ func slicestr(a interface{}, startEnd ...interface{}) (string, error) {
 
 }
 
+// hasPrefix tests whether the input s begins with prefix.
+func hasPrefix(s, prefix interface{}) (bool, error) {
+       ss, err := cast.ToStringE(s)
+       if err != nil {
+               return false, err
+       }
+
+       sp, err := cast.ToStringE(prefix)
+       if err != nil {
+               return false, err
+       }
+
+       return strings.HasPrefix(ss, sp), nil
+}
+
 // substr extracts parts of a string, beginning at the character at the specified
 // position, and returns the specified number of characters.
 //
@@ -2060,7 +2075,7 @@ func initFuncMap() {
                "getJSON":       getJSON,
                "getenv":        func(varName string) string { return os.Getenv(varName) },
                "gt":            gt,
-               "hasPrefix":     func(a, b string) bool { return strings.HasPrefix(a, b) },
+               "hasPrefix":     hasPrefix,
                "highlight":     highlight,
                "htmlEscape":    htmlEscape,
                "htmlUnescape":  htmlUnescape,
index f94ec6a79d6f320a03ec8791a7d607b61915673d..c5fb4c03da95d236c773a6b0e8db6022e0539a6e 100644 (file)
@@ -804,6 +804,33 @@ func TestSlicestr(t *testing.T) {
        }
 }
 
+func TestHasPrefix(t *testing.T) {
+       cases := []struct {
+               s      interface{}
+               prefix interface{}
+               want   interface{}
+               isErr  bool
+       }{
+               {"abcd", "ab", true, false},
+               {"abcd", "cd", false, false},
+               {template.HTML("abcd"), "ab", true, false},
+               {template.HTML("abcd"), "cd", false, false},
+               {template.HTML("1234"), 12, true, false},
+               {template.HTML("1234"), 34, false, false},
+               {[]byte("abcd"), "ab", true, false},
+       }
+
+       for i, c := range cases {
+               res, err := hasPrefix(c.s, c.prefix)
+               if (err != nil) != c.isErr {
+                       t.Fatalf("[%d] unexpected isErr state: want %v, got %v, err = %v", i, c.isErr, err != nil, err)
+               }
+               if res != c.want {
+                       t.Errorf("[%d] want %v, got %v", i, c.want, res)
+               }
+       }
+}
+
 func TestSubstr(t *testing.T) {
        var err error
        var n int