renderer

package module
Version: v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2019 License: MIT Imports: 14 Imported by: 11

README

Package renderer

Build Status Project status Go Report Card Coverage Status GoDoc License

Simple, lightweight and faster response (JSON, JSONP, XML, YAML, HTML, File) rendering package for Go

Installation

Install the package using

$ go get github.com/thedevsaddam/renderer/...
Usage

To use the package import it in your *.go code

import "github.com/thedevsaddam/renderer"
Example
package main

import (
	"io"
	"log"
	"net/http"
	"os"

	"github.com/thedevsaddam/renderer"
)

func main() {
	rnd := renderer.New()

	mux := http.NewServeMux()

	usr := struct {
		Name string
		Age  int
	}{"John Doe", 30}

	// serving String as text/plain
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		rnd.String(w, http.StatusOK, "Welcome to renderer")
	})

	// serving success but no content
	mux.HandleFunc("/no-content", func(w http.ResponseWriter, r *http.Request) {
		rnd.NoContent(w)
	})

	// serving string as html
	mux.HandleFunc("/html-string", func(w http.ResponseWriter, r *http.Request) {
		rnd.HTMLString(w, http.StatusOK, "<h1>Hello Renderer!</h1>")
	})

	// serving JSON
	mux.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) {
		rnd.JSON(w, http.StatusOK, usr)
	})

	// serving JSONP
	mux.HandleFunc("/jsonp", func(w http.ResponseWriter, r *http.Request) {
		rnd.JSONP(w, http.StatusOK, "callback", usr)
	})

	// serving XML
	mux.HandleFunc("/xml", func(w http.ResponseWriter, r *http.Request) {
		rnd.XML(w, http.StatusOK, usr)
	})

	// serving YAML
	mux.HandleFunc("/yaml", func(w http.ResponseWriter, r *http.Request) {
		rnd.YAML(w, http.StatusOK, usr)
	})

	// serving File as arbitary binary data
	mux.HandleFunc("/binary", func(w http.ResponseWriter, r *http.Request) {
		var reader io.Reader
		reader, _ = os.Open("../README.md")
		rnd.Binary(w, http.StatusOK, reader, "readme.md", true)
	})

	// serving File as inline
	mux.HandleFunc("/file-inline", func(w http.ResponseWriter, r *http.Request) {
		rnd.FileView(w, http.StatusOK, "../README.md", "readme.md")
	})

	// serving File as attachment
	mux.HandleFunc("/file-download", func(w http.ResponseWriter, r *http.Request) {
		rnd.FileDownload(w, http.StatusOK, "../README.md", "readme.md")
	})

	// serving File from reader as inline
	mux.HandleFunc("/file-reader", func(w http.ResponseWriter, r *http.Request) {
		var reader io.Reader
		reader, _ = os.Open("../README.md")
		rnd.File(w, http.StatusOK, reader, "readme.md", true)
	})

	// serving custom response using render and chaining methods
	mux.HandleFunc("/render", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set(renderer.ContentType, renderer.ContentText)
		rnd.Render(w, http.StatusOK, []byte("Send the message as text response"))
	})

	port := ":9000"
	log.Println("Listening on port", port)
	http.ListenAndServe(port, mux)
}

How to render html template?

Well, you can parse html template using HTML, View, Template any of these method. These are based on html/template package.

When using Template method you can simply pass the base layouts, templates path as a slice of string.

Template example

You can parse template on the fly using Template method. You can set delimiter, inject FuncMap easily.

template/layout.tmpl

<html>
  <head>
    <title>{{ template "title" . }}</title>
  </head>
  <body>
    {{ template "content" . }}
  </body>
  {{ block "sidebar" .}}{{end}}
</html>

template/index.tmpl

{{ define "title" }}Home{{ end }}

{{ define "content" }}
  <h1>Hello, {{ .Name | toUpper }}</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
{{ end }}

template/partial.tmpl

{{define "sidebar"}}
  simple sidebar code
{{end}}

template.go

package main

import (
	"html/template"
	"log"
	"net/http"
	"strings"

	"github.com/thedevsaddam/renderer"
)

var rnd *renderer.Render

func init() {
	rnd = renderer.New()
}

func toUpper(s string) string {
	return strings.ToUpper(s)
}

func handler(w http.ResponseWriter, r *http.Request) {
	usr := struct {
		Name string
		Age  int
	}{"john doe", 30}

	tpls := []string{"template/layout.tmpl", "template/index.tmpl", "template/partial.tmpl"}
	rnd.FuncMap(template.FuncMap{
		"toUpper": toUpper,
	})
	err := rnd.Template(w, http.StatusOK, tpls, usr)
	if err != nil {
		log.Fatal(err) //respond with error page or message
	}
}

func main() {
	http.HandleFunc("/", handler)
	log.Println("Listening port: 9000")
	http.ListenAndServe(":9000", nil)
}

HTML example

When using HTML you can parse a template directory using pattern and call the template by their name. See the example code below:

html/index.html

{{define "indexPage"}}
    <html>
    {{template "header"}}
    <body>
        <h3>Index</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
    </body>
    {{template "footer"}}
    </html>
{{end}}

html/header.html

{{define "header"}}
     <head>
         <title>Header</title>
         <h1>Header section</h1>
     </head>
{{end}}

html/footer.html

{{define "footer"}}
     <footer>Copyright &copy; 2020</footer>
{{end}}

html.go

package main

import (
	"log"
	"net/http"

	"github.com/thedevsaddam/renderer"
)

var rnd *renderer.Render

func init() {
	rnd = renderer.New(
		renderer.Options{
			ParseGlobPattern: "html/*.html",
		},
	)
}

func handler(w http.ResponseWriter, r *http.Request) {
	err := rnd.HTML(w, http.StatusOK, "indexPage", nil)
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	http.HandleFunc("/", handler)
	log.Println("Listening port: 9000")
	http.ListenAndServe(":9000", nil)
}

View example

When using View for parsing template you can pass multiple layout and templates. Here template name will be the file name. See the example to get the idea.

view/base.lout

<html>
  <head>
     <title>{{block "title" .}} {{end}}</title>
  </head>
  <body>
    {{ template "content" . }}
  </body>
</html>

view/home.tpl

{{define "title"}}Home{{end}}
{{define "content"}}
<h3>Home page</h3>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About Me</a></li>
    </ul>
    <p>
    Lorem ipsum dolor sit amet</p>
{{end}}

view/about.tpl

{{define "title"}}About Me{{end}}
{{define "content"}}
<h2>This is About me page.</h2>
<ul>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
</ul>
<p><a href="/">Home</a></p>
{{end}}

view.go

package main

import (
	"log"
	"net/http"

	"github.com/thedevsaddam/renderer"
)

var rnd *renderer.Render

func init() {
	rnd = renderer.New(renderer.Options{
		TemplateDir: "view",
	})
}

func home(w http.ResponseWriter, r *http.Request) {
	err := rnd.View(w, http.StatusOK, "home", nil)
	if err != nil {
		log.Fatal(err)
	}
}

func about(w http.ResponseWriter, r *http.Request) {
	err := rnd.View(w, http.StatusOK, "about", nil)
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	http.HandleFunc("/", home)
	http.HandleFunc("/about", about)
	log.Println("Listening port: 9000\n / is root \n /about is about page")
	http.ListenAndServe(":9000", nil)
}

Note: This is a wrapper on top of go built-in packages to provide syntactic sugar.

Contribution

Your suggestions will be more than appreciated. Read the contribution guide here

See all contributors
Read API doc to know about Available options and Methods
License

The renderer is an open-source software licensed under the MIT License.

Documentation

Overview

Package renderer documentaton contains the API for this package please follow the link below

Index

Constants

View Source
const (
	// ContentType represents content type
	ContentType string = "Content-Type"
	// ContentJSON represents content type application/json
	ContentJSON string = "application/json"
	// ContentJSONP represents content type application/javascript
	ContentJSONP string = "application/javascript"
	// ContentXML represents content type application/xml
	ContentXML string = "application/xml"
	// ContentYAML represents content type application/x-yaml
	ContentYAML string = "application/x-yaml"
	// ContentHTML represents content type text/html
	ContentHTML string = "text/html"
	// ContentText represents content type text/plain
	ContentText string = "text/plain"
	// ContentBinary represents content type application/octet-stream
	ContentBinary string = "application/octet-stream"

	// ContentDisposition describes contentDisposition
	ContentDisposition string = "Content-Disposition"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type M

type M map[string]interface{}

M describes handy type that represents data to send as response

type Options

type Options struct {
	// Charset represents the Response charset; default: utf-8
	Charset string
	// ContentJSON represents the Content-Type for JSON
	ContentJSON string
	// ContentJSONP represents the Content-Type for JSONP
	ContentJSONP string
	// ContentXML represents the Content-Type for XML
	ContentXML string
	// ContentYAML represents the Content-Type for YAML
	ContentYAML string
	// ContentHTML represents the Content-Type for HTML
	ContentHTML string
	// ContentText represents the Content-Type for Text
	ContentText string
	// ContentBinary represents the Content-Type for octet-stream
	ContentBinary string

	// UnEscapeHTML set UnEscapeHTML for JSON; default false
	UnEscapeHTML bool
	// DisableCharset set DisableCharset in Response Content-Type
	DisableCharset bool
	// Debug set the debug mode. if debug is true then every time "VIEW" call parse the templates
	Debug bool
	// JSONIndent set JSON Indent in response; default false
	JSONIndent bool
	// XMLIndent set XML Indent in response; default false
	XMLIndent bool

	// JSONPrefix set Prefix in JSON response
	JSONPrefix string
	// XMLPrefix set Prefix in XML response
	XMLPrefix string

	// TemplateDir set the Template directory
	TemplateDir string
	// TemplateExtension set the Template extension
	TemplateExtension string
	// LeftDelim set template left delimiter default is {{
	LeftDelim string
	// RightDelim set template right delimiter default is }}
	RightDelim string
	// LayoutExtension set the Layout extension
	LayoutExtension string
	// FuncMap contain function map for template
	FuncMap []template.FuncMap
	// ParseGlobPattern contain parse glob pattern
	ParseGlobPattern string
}

Options describes an option type

type Render

type Render struct {
	// contains filtered or unexported fields
}

Render describes a renderer type

func New

func New(opts ...Options) *Render

New return a new instance of a pointer to Render

func (*Render) Binary

func (r *Render) Binary(w http.ResponseWriter, status int, reader io.Reader, filename string, inline bool) error

Binary serve file as application/octet-stream response; you may add ContentDisposition by your own.

func (*Render) Charset

func (r *Render) Charset(c string) *Render

Charset change the Charset for response on the fly

func (*Render) Delims

func (r *Render) Delims(left, right string) *Render

Delims set template delimiter on the fly

func (*Render) DisableCharset

func (r *Render) DisableCharset(b bool) *Render

DisableCharset change the DisableCharset for JSON on the fly

func (*Render) EscapeHTML

func (r *Render) EscapeHTML(b bool) *Render

EscapeHTML change the EscapeHTML for JSON on the fly

func (*Render) File

func (r *Render) File(w http.ResponseWriter, status int, reader io.Reader, filename string, inline bool) error

File serve file as response from io.Reader

func (*Render) FileDownload

func (r *Render) FileDownload(w http.ResponseWriter, status int, fpath, name string) error

FileDownload serve file as response with content-disposition value attachment

func (*Render) FileView

func (r *Render) FileView(w http.ResponseWriter, status int, fpath, name string) error

FileView serve file as response with content-disposition value inline

func (*Render) FuncMap

func (r *Render) FuncMap(fmap template.FuncMap) *Render

FuncMap set template FuncMap on the fly

func (*Render) HTML

func (r *Render) HTML(w http.ResponseWriter, status int, name string, v interface{}) error

HTML render html from template.Glob patterns and execute template by name. See README.md for detail example.

func (*Render) HTMLString

func (r *Render) HTMLString(w http.ResponseWriter, status int, html string) error

HTMLString render string as html. Note: You must provide trusted html when using this method

func (*Render) JSON

func (r *Render) JSON(w http.ResponseWriter, status int, v interface{}) error

JSON serve data as JSON as response

func (*Render) JSONIndent

func (r *Render) JSONIndent(b bool) *Render

JSONIndent change the JSONIndent for JSON on the fly

func (*Render) JSONP

func (r *Render) JSONP(w http.ResponseWriter, status int, callback string, v interface{}) error

JSONP serve data as JSONP response

func (*Render) NoContent

func (r *Render) NoContent(w http.ResponseWriter) error

NoContent serve success but no content response

func (*Render) Render

func (r *Render) Render(w http.ResponseWriter, status int, v interface{}) error

Render serve raw response where you have to build the headers, body

func (*Render) String

func (r *Render) String(w http.ResponseWriter, status int, v interface{}) error

String serve string content as text/plain response

func (*Render) Template

func (r *Render) Template(w http.ResponseWriter, status int, tpls []string, v interface{}) error

Template build html from template and serve html content as response. See README.md for detail example.

func (*Render) View

func (r *Render) View(w http.ResponseWriter, status int, name string, v interface{}) error

View build html from template directory and serve html content as response. See README.md for detail example.

func (*Render) XML

func (r *Render) XML(w http.ResponseWriter, status int, v interface{}) error

XML serve data as XML response

func (*Render) XMLIndent

func (r *Render) XMLIndent(b bool) *Render

XMLIndent change the XMLIndent for XML on the fly

func (*Render) YAML

func (r *Render) YAML(w http.ResponseWriter, status int, v interface{}) error

YAML serve data as YAML response

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL