/
soyweb.go
60 lines (47 loc) · 1.09 KB
/
soyweb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Package soyweb is a simple development server that serves the given template.
Invoke it like so:
go get github.com/robfig/soy/soyweb
soyweb test.soy
It will attempt to execute the "soyweb.soyweb" template found in the given file.
Parameters may be provided to the template in the URL query string.
*/
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/robfig/soy"
"github.com/robfig/soy/data"
)
var port = flag.Int("port", 9812, "port on which to listen")
func main() {
fmt.Print("Listening on :", *port, "...")
log.Fatal(http.ListenAndServe(
fmt.Sprintf(":%d", *port),
http.HandlerFunc(handler)))
}
func handler(res http.ResponseWriter, req *http.Request) {
var tofu, err = soy.NewBundle().
AddTemplateFile(os.Args[1]).
CompileToTofu()
if err != nil {
http.Error(res, err.Error(), 500)
return
}
var m = make(data.Map)
for k, v := range req.URL.Query() {
m[k] = data.String(v[0])
}
var buf bytes.Buffer
err = tofu.Render(&buf, "soyweb.soyweb", m)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
io.Copy(res, &buf)
}