Adds flexible render system
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Manu Mtz-Almeida · committed by Manu Mtz-Almeida · parent 94bc35b · Browse files · 3 files·+105 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+105 added−42 removed
- other:+105 added−42 removed
Provenance
- Commit
5ea7a92- Tree
952cc66- Author
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Committer
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Parent
94bc35b
3 files changed+105 added−42 removed
added:render/render.go+69 added
1+package render2+3+import (4+ "encoding/json"5+ "encoding/xml"6+ "fmt"7+ "html/template"8+ "net/http"9+)10+11+type (12+ Render interface {13+ Render(http.ResponseWriter, int, ...interface{}) error14+ }15+16+ // JSON binding17+ jsonRender struct{}18+19+ // XML binding20+ xmlRender struct{}21+22+ // Plain text23+ plainRender struct{}24+25+ // form binding26+ HTMLRender struct {27+ Template *template.Template28+ }29+)30+31+var (32+ JSON = jsonRender{}33+ XML = xmlRender{}34+ Plain = plainRender{}35+)36+37+func writeHeader(w http.ResponseWriter, code int, contentType string) {38+ if code >= 0 {39+ w.Header().Set("Content-Type", contentType)40+ w.WriteHeader(code)41+ }42+}43+44+func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {45+ writeHeader(w, code, "application/xml")46+ encoder := json.NewEncoder(w)47+ return encoder.Encode(data[0])48+}49+50+func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {51+ writeHeader(w, code, "application/xml")52+ encoder := xml.NewEncoder(w)53+ return encoder.Encode(data[0])54+}55+56+func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {57+ writeHeader(w, code, "text/html")58+ file := data[0].(string)59+ obj := data[1]60+ return html.Template.ExecuteTemplate(w, file, obj)61+}62+63+func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {64+ writeHeader(w, code, "text/plain")65+ format := data[0].(string)66+ args := data[1].([]interface{})67+ _, err := w.Write([]byte(fmt.Sprintf(format, args)))68+ return err69+}modified:deprecated.go+5 added
29 unmodified lines30 // router.ServeFiles("/src/*filepath", http.Dir("/var/www"))31 func (engine *Engine) ServeFiles(path string, root http.FileSystem) {32 engine.router.ServeFiles(path, root)33 }34+35+// DEPRECATED use gin.LoadHTMLGlob() or gin.LoadHTMLFiles() instead36+func (engine *Engine) LoadHTMLTemplates(pattern string) {37+ engine.LoadHTMLGlob(pattern)38+}modified:gin.go+31 added-42 removed
1 package gin2 3 import (4 "bytes"5- "encoding/json"5 "encoding/xml"6 "errors"7 "fmt"8 "github.com/gin-gonic/gin/binding"9+ "github.com/gin-gonic/gin/render"10 "github.com/julienschmidt/httprouter"11 "html/template"12 "log"13 "math"56 unmodified lines70 71 // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.72 Engine struct {73 *RouterGroup74- HTMLTemplates *template.Template75- cache sync.Pool76- handlers404 []HandlerFunc77- router *httprouter.Router74+ HTMLRender render.Render75+ cache sync.Pool76+ handlers404 []HandlerFunc77+ router *httprouter.Router78 }79 )80 81 // Allows type H to be used with xml.Marshal64 unmodified lines146 engine.Use(Recovery(), Logger())147 return engine148 }149 150-func (engine *Engine) LoadHTMLTemplates(pattern string) {151- engine.HTMLTemplates = template.Must(template.ParseGlob(pattern))150+func (engine *Engine) LoadHTMLGlob(pattern string) {151+ templ := template.Must(template.ParseGlob(pattern))152+ engine.SetHTTPTemplate(templ)153 }154 155+func (engine *Engine) LoadHTMLFiles(files ...string) {156+ templ := template.Must(template.ParseFiles(files...))157+ engine.SetHTTPTemplate(templ)158+}159+160+func (engine *Engine) SetHTTPTemplate(templ *template.Template) {161+ engine.HTMLRender = render.HTMLRender{162+ Template: templ,163+ }164+}165+166 // Adds handlers for NotFound. It return a 404 code by default.167 func (engine *Engine) NotFound404(handlers ...HandlerFunc) {168 engine.handlers404 = handlers169 }282 unmodified lines452 }453 return true454 }455 444-// Serializes the given struct as JSON into the response body in a fast and efficient way.445-// It also sets the Content-Type as "application/json".446-func (c *Context) JSON(code int, obj interface{}) {447- c.Writer.Header().Set("Content-Type", MIMEJSON)448- if code >= 0 {449- c.Writer.WriteHeader(code)450- }451- encoder := json.NewEncoder(c.Writer)452- if err := encoder.Encode(obj); err != nil {456+func (c *Context) Render(code int, render render.Render, obj ...interface{}) {457+ if err := render.Render(c.Writer, code, obj); err != nil {458 c.ErrorTyped(err, ErrorTypeInternal, obj)459 c.Abort(500)460 }461 }462 463+// Serializes the given struct as JSON into the response body in a fast and efficient way.464+// It also sets the Content-Type as "application/json".465+func (c *Context) JSON(code int, obj interface{}) {466+ c.Render(code, render.JSON, obj)467+}468+469 // Serializes the given struct as XML into the response body in a fast and efficient way.470 // It also sets the Content-Type as "application/xml".471 func (c *Context) XML(code int, obj interface{}) {461- c.Writer.Header().Set("Content-Type", MIMEXML)462- if code >= 0 {463- c.Writer.WriteHeader(code)464- }465- encoder := xml.NewEncoder(c.Writer)466- if err := encoder.Encode(obj); err != nil {467- c.ErrorTyped(err, ErrorTypeInternal, obj)468- c.Abort(500)469- }472+ c.Render(code, render.XML, obj)473 }474 475 // Renders the HTTP template specified by its file name.476 // It also updates the HTTP code and sets the Content-Type as "text/html".477 // See http://golang.org/doc/articles/wiki/475-func (c *Context) HTML(code int, name string, data interface{}) {476- c.Writer.Header().Set("Content-Type", MIMEHTML)477- if code >= 0 {478- c.Writer.WriteHeader(code)479- }480- if err := c.Engine.HTMLTemplates.ExecuteTemplate(c.Writer, name, data); err != nil {481- c.ErrorTyped(err, ErrorTypeInternal, H{482- "name": name,483- "data": data,484- })485- c.Abort(500)486- }478+func (c *Context) HTML(code int, name string, obj interface{}) {479+ c.Render(code, c.Engine.HTMLRender, name, obj)480 }481 482 // Writes the given string into the response body and sets the Content-Type to "text/plain".483 func (c *Context) String(code int, format string, values ...interface{}) {491- c.Writer.Header().Set("Content-Type", MIMEPlain)492- if code >= 0 {493- c.Writer.WriteHeader(code)494- }495- c.Writer.Write([]byte(fmt.Sprintf(format, values...)))484+ c.Render(code, render.Plain, format, values)485 }486 487 // Writes some data into the body stream and updates the HTTP code.488 func (c *Context) Data(code int, contentType string, data []byte) {8 unmodified lines