Slide 1

Slide 1 text

3  Things  You  May  Not   Know  About  The  Go   Template  Engine   Chang  Sau  Sheong   Feb  2015  

Slide 2

Slide 2 text

Obligatory  stuff  

Slide 3

Slide 3 text

What  is  a  template   engine?  

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

Where’s  Go  template  engine?   Logic-­‐less   Go   template   engine   Embedded   logic   Mustache,  Handlebars  etc   JSP,  Haml,  Jade  etc  

Slide 7

Slide 7 text

How  does  the  Go  template   engine  work?  

Slide 8

Slide 8 text

text/template   html/template  

Slide 9

Slide 9 text

Parse   template   Execute   template  

Slide 10

Slide 10 text

Go Web Programming {{ . }}

Slide 11

Slide 11 text

package main import ( "net/http" "html/template" ) func process(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("tmpl.html") t.Execute(w, "Hello World!") } func main() { server := http.Server{ Addr: "127.0.0.1:8080", } http.HandleFunc("/process", process) server.ListenAndServe() }

Slide 12

Slide 12 text

The  Go  template  engine  is   kinda  cool  

Slide 13

Slide 13 text

1.  Pipelines  

Slide 14

Slide 14 text

{{ p1 | p2 | p3 }}

Slide 15

Slide 15 text

Go Web Programming {{ 12.3456 | printf "%.2f" }}

Slide 16

Slide 16 text

2.  FuncTons  

Slide 17

Slide 17 text

func formatDate(t time.Time) string { layout := "2006-01-02" return t.Format(layout) } func process(w http.ResponseWriter, r *http.Request) { funcMap := template.FuncMap { "fdate": formatDate } t := template.New("tmpl.html").Funcs(funcMap) t, _ = t.ParseFiles("tmpl.html") t.Execute(w, time.Now()) }

Slide 18

Slide 18 text

Go Web Programming
The date/time is {{ fdate . }}

Slide 19

Slide 19 text

Go Web Programming
The date/time is {{ . | fdate }}

Slide 20

Slide 20 text

3.  Context  aware  

Slide 21

Slide 21 text

func process(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("tmpl.html") content := `I asked: "What's up?"` t.Execute(w, content) }

Slide 22

Slide 22 text

Go Web Programming
{{ . }}

Slide 23

Slide 23 text

Go Web Programming
I asked: <i>"What's up?"</ i>

Slide 24

Slide 24 text

Slide 25

Slide 25 text

XSS  

Slide 26

Slide 26 text

XSS  Demo    

Slide 27

Slide 27 text

hWp://manning.com/chang  

Slide 28

Slide 28 text

Thank  you   [email protected]   @sausheong