Skip to content

Commit

Permalink
implement ctx.Render (#107)
Browse files Browse the repository at this point in the history
* implement render

* add test
  • Loading branch information
acoshift committed Sep 23, 2023
1 parent e2e7c13 commit 5eaaa34
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
35 changes: 35 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"html/template"
"io"
"net"
"net/http"
Expand Down Expand Up @@ -266,6 +267,40 @@ func (ctx *Context) Component(name string, data any) error {
return ctx.CopyFrom(buf)
}

// Render renders html template
func (ctx *Context) Render(tmpl string, data any) error {
// TODO: cache template
// TODO: use pre-defined template func
t, err := template.New("").Parse(tmpl)
if err != nil {
return err
}

return ctx.executeTemplate(t, data)
}

func (ctx *Context) executeTemplate(t *template.Template, data any) error {
if !ctx.etag {
ctx.setContentType("text/html; charset=utf-8")
return filterRenderError(t.Execute(ctx.w, data))
}

buf := getBytes()
defer putBytes(buf)

err := t.Execute(buf, data)
if err != nil {
return err
}

if ctx.setETag(buf.Bytes()) {
return nil
}

ctx.setContentType("text/html; charset=utf-8")
return ctx.CopyFrom(buf)
}

func (ctx *Context) setContentType(value string) {
if len(ctx.w.Header().Get("Content-Type")) == 0 {
ctx.w.Header().Set("Content-Type", value)
Expand Down
13 changes: 13 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,19 @@ func TestContext(t *testing.T) {
assert.Equal(t, w.Body.String(), "hello, world")
})

t.Run("Render", func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/", nil)

app := hime.New()
ctx := hime.NewAppContext(app, w, r)

assert.NoError(t, ctx.Render(`hello, {{.}}`, "world"))
assert.Equal(t, w.Code, http.StatusOK)
assert.Equal(t, w.Header().Get("Content-Type"), "text/html; charset=utf-8")
assert.Equal(t, w.Body.String(), "hello, world")
})

t.Run("BindJSON", func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader([]byte(`{"a":1}`)))
Expand Down

0 comments on commit 5eaaa34

Please sign in to comment.