Skip to content

Commit

Permalink
#103 added custom render method and adapter func too (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeevatkm committed Aug 23, 2017
1 parent fae4b30 commit 0325b9e
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
15 changes: 14 additions & 1 deletion render.go
Expand Up @@ -37,11 +37,15 @@ type (
// Data type used for convenient data type of map[string]interface{}
Data map[string]interface{}

// Render interface
// Render interface to various rendering classifcation for HTTP responses.
Render interface {
Render(io.Writer) error
}

// RenderFunc type is an adapter to allow the use of regular function as
// custom Render.
RenderFunc func(w io.Writer) error

// Text renders the response as plain text
Text struct {
Format string
Expand Down Expand Up @@ -75,6 +79,15 @@ type (
}
)

//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// RenderFunc methods
//___________________________________

// Render method is implementation of Render interface in the adapter type.
func (rf RenderFunc) Render(w io.Writer) error {
return rf(w)
}

//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Plain Text Render methods
//___________________________________
Expand Down
7 changes: 7 additions & 0 deletions reply.go
Expand Up @@ -304,6 +304,13 @@ func (r *Reply) Error(err *Error) *Reply {
return r
}

// Render method is used for custom rendering by implementing interface
// `aah.Render`.
func (r *Reply) Render(rdr Render) *Reply {
r.Rdr = rdr
return r
}

//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Reply methods
//___________________________________
Expand Down
40 changes: 40 additions & 0 deletions reply_test.go
Expand Up @@ -5,7 +5,9 @@
package aah

import (
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
Expand Down Expand Up @@ -368,6 +370,44 @@ func TestReplyCookie(t *testing.T) {
releaseReply(re1)
}

// customRender implements the interface `aah.Render`.
type customRender struct {
// ... your fields goes here
}

func (cr *customRender) Render(w io.Writer) error {
fmt.Fprint(w, "This is custom render struct")
return nil
}

func TestReplyCustomRender(t *testing.T) {
re := acquireReply()
buf := acquireBuffer()

re.Render(&customRender{})
err := re.Rdr.Render(buf)
assert.Nil(t, err)
assert.Equal(t, "This is custom render struct", buf.String())

releaseBuffer(buf)
releaseReply(re)

// Render func
re = acquireReply()
buf = acquireBuffer()

re.Render(RenderFunc(func(w io.Writer) error {
fmt.Fprint(w, "This is custom render func")
return nil
}))
err = re.Rdr.Render(buf)
assert.Nil(t, err)
assert.Equal(t, "This is custom render func", buf.String())

releaseBuffer(buf)
releaseReply(re)
}

func getReplyRenderCfg() *config.Config {
cfg, _ := config.ParseString(`
render {
Expand Down

0 comments on commit 0325b9e

Please sign in to comment.