diff --git a/README.md b/README.md index 284f1fc..110bfa3 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,28 @@ func(req *express.Request, res *express.Response){ } ``` +## HTML Template + +Use [standard Golang http templates](https://golang.org/pkg/html/template/) to render response page. + +For example, you have a template file `index.html` in `templates` directory: + +```html +

{{.Name}}

+``` + +Fill the context and provide a path to the template file: + +```go +func(req *express.Request, res *express.Response){ + type TmplContext struct{ + Name string + } + data := TmplContext{"Rob"} + res.Render("template.html", &data) +} +``` + ## Safe Cleanup on exit Newer version of goexpress provides three new methods namely `express.ShutdownTimeout`, `express.BeforeShutdown` and `express.Shutdown`, these methods can be utilised to do cleanup before the server shuts down. diff --git a/examples/render/render.go b/examples/render/render.go new file mode 100644 index 0000000..7179598 --- /dev/null +++ b/examples/render/render.go @@ -0,0 +1,23 @@ +package main + +import ( + "github.com/DronRathore/goexpress" +) + +type Context struct { + Greeting string + Subject string +} + +func main() { + express := goexpress.Express() + // return rendered template + express.Get("/", func(req goexpress.Request, res goexpress.Response) { + data := Context{ + Greeting: "Hello", + Subject: "world", + } + res.Render("template.html", data) + }) + express.Start("8080") +} diff --git a/examples/render/template.html b/examples/render/template.html new file mode 100644 index 0000000..6e81c4d --- /dev/null +++ b/examples/render/template.html @@ -0,0 +1,5 @@ + + +

{{.Greeting}}, {{.Subject}}!

+ + diff --git a/interface.go b/interface.go index bbd01b4..5fe08d3 100644 --- a/interface.go +++ b/interface.go @@ -53,6 +53,7 @@ type Response interface { SendFile(url string, noCache bool) bool WriteBytes(bytes []byte) error Write(content string) Response + Render(path string, data interface{}) } // Header defines HTTP header interface diff --git a/response.go b/response.go index 90a31ff..e89df11 100644 --- a/response.go +++ b/response.go @@ -3,11 +3,13 @@ package goexpress import ( + "bytes" "bufio" "crypto/md5" "encoding/hex" "encoding/json" "fmt" + "html/template" "io" "log" "net" @@ -307,3 +309,27 @@ func (res *response) Header() Header { func (res *response) Cookie() Cookie { return res.cookie } + +// Render returns rendered HTML template +func (res *response) Render(file string, data interface{}) { + tmpl, err := template.ParseFiles(file) + if err != nil { + log.Print("Template not found ", err) + res.header.SetStatus(500) + res.header.FlushHeaders() + res.End() + return + } + + var tpl bytes.Buffer + err = tmpl.Execute(&tpl, data) + if err != nil { + log.Print("Template render failed ", err) + res.header.SetStatus(500) + res.header.FlushHeaders() + res.End() + return + } + res.WriteBytes(tpl.Bytes()) +} +