Add RenderGomponent function to echoutil package

This commit is contained in:
Luis Eduardo Jeréz Girón
2024-07-22 00:14:13 -06:00
parent 3b91a5d758
commit 4929a12b9b
2 changed files with 79 additions and 0 deletions
@@ -0,0 +1,24 @@
package echoutil
import (
"bytes"
"io"
"net/http"
"github.com/labstack/echo/v4"
)
type renderer interface {
Render(w io.Writer) error
}
// RenderGomponent renders a gomponents component to the response of
// the echo context.
func RenderGomponent(c echo.Context, code int, component renderer) error {
buf := bytes.Buffer{}
err := component.Render(&buf)
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
return c.HTML(code, buf.String())
}
@@ -0,0 +1,55 @@
package echoutil
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
type okRenderer struct{}
func (m *okRenderer) Render(w io.Writer) error {
_, err := w.Write([]byte("render ok"))
return err
}
type nokRenderer struct{}
func (m *nokRenderer) Render(w io.Writer) error {
return errors.New("render nok")
}
func TestRenderGomponent(t *testing.T) {
// Setup renderer mocks
okRendererIns := new(okRenderer)
nokRendererIns := new(nokRenderer)
t.Run("Successful Render", func(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := RenderGomponent(c, http.StatusOK, okRendererIns)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, c.Response().Status)
assert.Equal(t, "render ok", rec.Body.String())
})
t.Run("Unsuccessful Render", func(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := RenderGomponent(c, http.StatusOK, nokRendererIns)
assert.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.Equal(t, "render nok", rec.Body.String())
})
}