Browse Source

First version

Piotr Czajkowski 4 years ago
parent
commit
fdd2b783ac
2 changed files with 85 additions and 0 deletions
  1. 22 0
      stringFromTemplate.go
  2. 63 0
      stringFromTemplate_test.go

+ 22 - 0
stringFromTemplate.go

@@ -0,0 +1,22 @@
+package stringFromTemplate
+
+import (
+	"strings"
+	"text/template"
+)
+
+func ToString(templateString string, object interface{}) string {
+	var buffer strings.Builder
+
+	tmpl, err := template.New("default").Parse(templateString)
+	if err != nil {
+		return err.Error()
+	}
+
+	err = tmpl.Execute(&buffer, object)
+	if err != nil {
+		return err.Error()
+	}
+
+	return buffer.String()
+}

+ 63 - 0
stringFromTemplate_test.go

@@ -0,0 +1,63 @@
+package stringFromTemplate
+
+import (
+	"testing"
+)
+
+type Something struct {
+	First  int
+	Second string
+}
+
+const expected = `Something here 15
+And something else here and the string`
+
+func TestToString(t *testing.T) {
+	const templateString = `Something here {{.First}}
+And something else here {{.Second}}`
+
+	test := Something{First: 15, Second: "and the string"}
+
+	result := ToString(templateString, test)
+
+	if expected != result {
+		t.Errorf("%v", result)
+	} else {
+		t.Log("String constructed properly.")
+	}
+}
+
+func TestToStringBadTemplate(t *testing.T) {
+	const templateString = `Something here {{.First()}}
+And something else here {{.Second}}`
+
+	test := Something{First: 15, Second: "and the string"}
+
+	result := ToString(templateString, test)
+
+	if expected == result {
+		t.Error("It should fail on template parsing!")
+	} else {
+		t.Log(result)
+	}
+}
+
+func TestToStringBadObject(t *testing.T) {
+	const templateString = `Something here {{.First}}
+And something else here {{.Second}}`
+
+	type Something struct {
+		Third  int
+		Second string
+	}
+
+	test := Something{Third: 15, Second: "and the string"}
+
+	result := ToString(templateString, test)
+
+	if expected == result {
+		t.Error("It should fail!")
+	} else {
+		t.Log(result)
+	}
+}