From ac17ec792585fde692f7e34ad57a75ce373f7826 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luis=20Eduardo=20Jer=C3=A9z=20Gir=C3=B3n?= Date: Wed, 21 Aug 2024 21:46:37 -0600 Subject: [PATCH] Handle nil component in RenderGomponent: return NoContent response if component is nil; add corresponding unit test --- internal/util/echoutil/render_gomponent.go | 4 ++++ internal/util/echoutil/render_gomponent_test.go | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/internal/util/echoutil/render_gomponent.go b/internal/util/echoutil/render_gomponent.go index 0c9b9af..cb024e0 100644 --- a/internal/util/echoutil/render_gomponent.go +++ b/internal/util/echoutil/render_gomponent.go @@ -15,6 +15,10 @@ type renderer interface { // RenderGomponent renders a gomponents component to the response of // the echo context. func RenderGomponent(c echo.Context, code int, component renderer) error { + if component == nil { + return c.NoContent(code) + } + buf := bytes.Buffer{} err := component.Render(&buf) if err != nil { diff --git a/internal/util/echoutil/render_gomponent_test.go b/internal/util/echoutil/render_gomponent_test.go index af1c772..362c6f4 100644 --- a/internal/util/echoutil/render_gomponent_test.go +++ b/internal/util/echoutil/render_gomponent_test.go @@ -53,3 +53,15 @@ func TestRenderGomponent(t *testing.T) { assert.Equal(t, "render nok", rec.Body.String()) }) } + +func TestRenderNilGomponent(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, nil) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "", rec.Body.String()) +}