all repos — gomponents @ d78ed7efc7925a7a49cbf939fd45b1b2680a37f4

HTML components in pure Go

Add a Write function (#11)

Markus Wüstenberg markus@maragu.dk
Mon, 21 Sep 2020 11:27:37 +0200
commit

d78ed7efc7925a7a49cbf939fd45b1b2680a37f4

parent

8de5a685efbc6f13e606dcd70d15b757e3f9ad9a

2 files changed, 37 insertions(+), 0 deletions(-)

jump to
M gomponents.gogomponents.go
@@ -10,6 +10,7 @@ import (
 	"fmt"
 	"html/template"
+	"io"
 	"strings"
 )
 
@@ -114,3 +115,9 @@ return func() string { 		return t
 	}
 }
+
+// Write to the given io.Writer, returning any error.
+func Write(w io.Writer, n Node) error {
+	_, err := w.Write([]byte(n.Render()))
+	return err
+}
M gomponents_test.gogomponents_test.go
@@ -1,6 +1,8 @@ package gomponents_test
 
 import (
+	"errors"
+	"strings"
 	"testing"
 
 	g "github.com/maragudk/gomponents"
@@ -76,3 +78,31 @@ e := g.Raw("<div/>") 		assert.Equal(t, "<div/>", e)
 	})
 }
+
+type erroringWriter struct{}
+
+func (w *erroringWriter) Write(p []byte) (n int, err error) {
+	return 0, errors.New("don't want to write")
+}
+
+func TestWrite(t *testing.T) {
+	t.Run("writes to the writer", func(t *testing.T) {
+		e := g.El("div")
+		var b strings.Builder
+		err := g.Write(&b, e)
+		if err != nil {
+			t.FailNow()
+		}
+		if b.String() != e.Render() {
+			t.FailNow()
+		}
+	})
+
+	t.Run("errors on write error", func(t *testing.T) {
+		e := g.El("div")
+		err := g.Write(&erroringWriter{}, e)
+		if err == nil {
+			t.FailNow()
+		}
+	})
+}