• Stars
    star
    261
  • Rank 156,602 (Top 4 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 7 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

More Repositories

1

gojsonq

A simple Go package to Query over JSON/YAML/XML/CSV Data
Go
2,176
star
2

govalidator

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.
Go
1,311
star
3

docgen

Transform your postman collection to HTML/Markdown documentation
Go
963
star
4

laravel-schema

Display the connected database information from Terminal.
PHP
112
star
5

task

Terminal tasks todo with reminder tool for geek
Go
81
star
6

retry

Simple and easy retry mechanism package for Go
Go
66
star
7

dl

Command-line file downloader tool
Go
50
star
8

ubuntu-live-wallpaper

Live wallpaper changer for ubuntu. Inspired from chrome momentum extension
Python
44
star
9

lumen-route-list

Display all the registered route list in lumen application just like laravel.
PHP
36
star
10

orchid-micro

Golang boilerplate using gin-gonic framework and gorm for microservice
Go
30
star
11

todoapp

Tutorial purpose repository
Go
27
star
12

docgen-bin

Transform your postman collection to html documentation
26
star
13

slack-notifier

This script will help you to send slack scheduled notification (message)
Python
22
star
14

world-countries

Provide world country list with country code, city, states and flag
PHP
19
star
15

gomailer

Gomailer provides a simple email interface to integrate third party email services.
Go
14
star
16

bongo

Terminal based bengali calendar
Go
14
star
17

ponjika

Tiny bengali ponjika based on Gregorian date
Go
12
star
18

traffic

Thread safe load-balancer package for Golang
Go
11
star
19

orchid

A MVC style boilerplate for golang
Go
11
star
20

snapshot

Robust, Persistent, Key-Value (KV) store purely written in Golang
Go
11
star
21

radar

Package radar help to debug nested function call and Trace current file/line
Go
9
star
22

unpack

Go assignment by slice, array unpacking or destructuring
Go
9
star
23

q

[WIP] "q" a command-line tool to query JSON/XML/YAML/CSV document
Go
8
star
24

iter

Iter provides functionality like Python's range function to iterate over numbers and letters
Go
8
star
25

querybuilder

A fake query builder to demonstrate the factory and singleton pattern
Go
7
star
26

multiple_route

MultipleRoute generator is helpful create any number of routes for your large laravel project.
PHP
6
star
27

clean

[WIP] Trying to make a boilerplate for clean-architecture in Golang
Go
5
star
28

task_binaries

Task binary files
5
star
29

timezones

PHP supported timezones array
PHP
4
star
30

dictionary

Offline terminal dictionary
Go
3
star
31

dj1.9

learning django 1.9 with python 3
Python
3
star
32

vue1-learning

Playing with vue.js v1.0
HTML
3
star
33

thedevsaddam

Portfolio Page
3
star
34

enToBnDigit

English digit to bengali digit...
PHP
3
star
35

py-ghataghati

Just trying to figure out python
Python
3
star
36

py-app

Learning django
Python
3
star
37

thedevsaddam.github.io

Personal blog site
CSS
3
star
38

go-repl

GO REPL is a simple application promising to write/compile/run code in terminal, inspired by python shell
Go
3
star
39

pc-ready

Its a shell script that will setup essential software and development environment for your Ubuntu OS
Shell
3
star
40

vue-simple-todo

Simple vue todo
HTML
3
star
41

go-ladder

Database migration package for golang inspired by Laravel migration
3
star
42

dj-project

Learning django...
Python
3
star
43

erlang

Playing with Erlang
Erlang
2
star
44

files

Contains files for public repositories
2
star
45

homebrew-cli

Contains formula for different tools for mac
Ruby
2
star
46

es6

ECMAScript 6, also known as ECMAScript 2015
JavaScript
2
star
47

worker

Go
2
star
48

go_repl_binaries

GO REPL is a simple application promising to write/compile/run code in terminal, inspired by python shell
2
star
49

ubuntu-500px-wallpaper

Inspired from chrome momentum extension. Get new wallpaper from 500px popular section, each time restart the computer.
Shell
2
star
50

30-seconds-of-go

2
star
51

reactjs

Learning react js
JavaScript
2
star
52

tweet-release

Go
1
star
53

action

GitHub action to supercharge your pull requests workflows!
Go
1
star
54

assessment-200

Python
1
star
55

lo_

A modern Rust utility library delivering modularity, performance & extras proted from JavaScript Lodash
Rust
1
star