+ support custom render, pongo2 tested

This commit is contained in:
SCys 2015-11-09 00:24:18 +08:00
parent 52fcc5dbf6
commit 36dce1a73f
3 changed files with 56 additions and 7 deletions

View File

@ -341,6 +341,11 @@ func (c *Context) HTML(code int, name string, obj interface{}) {
c.Render(code, instance) c.Render(code, instance)
} }
func (c *Context) CustomRender(code int, name string, obj interface{}) {
instance := c.engine.CustomRender.Instance(name, obj)
c.Render(code, instance)
}
// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
// It also sets the Content-Type as "application/json". // It also sets the Content-Type as "application/json".
// WARNING: we recommend to use this only for development propuses since printing pretty JSON is // WARNING: we recommend to use this only for development propuses since printing pretty JSON is

5
gin.go
View File

@ -45,6 +45,7 @@ type (
Engine struct { Engine struct {
RouterGroup RouterGroup
HTMLRender render.HTMLRender HTMLRender render.HTMLRender
CustomRender render.CustomRender
allNoRoute HandlersChain allNoRoute HandlersChain
allNoMethod HandlersChain allNoMethod HandlersChain
noRoute HandlersChain noRoute HandlersChain
@ -147,6 +148,10 @@ func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
engine.HTMLRender = render.HTMLProduction{Template: templ} engine.HTMLRender = render.HTMLProduction{Template: templ}
} }
func (engine *Engine) SetCustomRenderFunc(f render.CustomRenderFunc) {
engine.CustomRender = render.CustomRenderProduction{f}
}
// Adds handlers for NoRoute. It return a 404 code by default. // Adds handlers for NoRoute. It return a 404 code by default.
func (engine *Engine) NoRoute(handlers ...HandlerFunc) { func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
engine.noRoute = handlers engine.noRoute = handlers

39
render/custom_render.go Normal file
View File

@ -0,0 +1,39 @@
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"net/http"
)
type (
CustomRenderFunc func(http.ResponseWriter, string, interface{}) error
CustomRender interface {
Instance(string, interface{}) Render
}
CustomRenderProduction struct {
RenderFunc CustomRenderFunc
}
Custom struct {
RenderFunc CustomRenderFunc
Name string
Data interface{}
}
)
func (r CustomRenderProduction) Instance(name string, data interface{}) Render {
return Custom{
RenderFunc: r.RenderFunc,
Name: name,
Data: data,
}
}
func (r Custom) Render(w http.ResponseWriter) error {
return r.RenderFunc(w, r.Name, r.Data)
}