mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-05-05 11:09:11 -05:00
Add RenderGomponent function to echoutil package
This commit is contained in:
@@ -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())
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user