15
15
package main
16
16
17
17
import (
18
+ "bytes"
18
19
"flag"
19
20
"fmt"
21
+ "io"
20
22
"log"
21
23
"net/http"
22
24
"os"
23
25
"path"
26
+ "strings"
27
+
28
+ "github.com/robfig/soy"
29
+ "github.com/robfig/soy/data"
30
+ "github.com/robfig/soy/soyhtml"
24
31
)
25
32
26
33
var (
27
34
cwd , _ = os .Getwd ()
28
35
webRoot = flag .String ("web-root" , cwd , "Root of the web file tree." )
29
36
host = flag .String ("host" , "127.0.0.1" , "By default, the server is only accessible via localhost. " +
30
37
"Set to 0.0.0.0 or empty string to open to all." )
31
- port = flag .String ("port" , getEnvWithDefault ("PORT" , "8080" ), "Port to listen on; $PORT env var overrides default value." )
38
+ port = flag .String ("port" , getEnvWithDefault ("PORT" , "8080" ), "Port to listen on; $PORT env var overrides default value." )
39
+ tofu * soyhtml.Tofu = nil
32
40
)
33
41
34
42
func getEnvWithDefault (varName , defaultValue string ) string {
@@ -38,14 +46,42 @@ func getEnvWithDefault(varName, defaultValue string) string {
38
46
return defaultValue
39
47
}
40
48
49
+ func dispatchHandler (rw http.ResponseWriter , req * http.Request ) {
50
+ if strings .HasSuffix (req .URL .Path , ".css" ) || strings .HasSuffix (req .URL .Path , ".js" ) {
51
+ staticFileHandler (rw , req )
52
+ } else if req .URL .Path == "/" {
53
+ indexHandler (rw , req )
54
+ } else {
55
+ http .Error (rw , fmt .Sprintf ("Not found: %s" , req .URL .Path ), 404 )
56
+ }
57
+ }
58
+
41
59
func indexHandler (rw http.ResponseWriter , req * http.Request ) {
42
- log .Printf ("Access log: %s %s" , req .Method , req .URL .Path )
60
+ log .Printf ("Access [index]: %s %s" , req .Method , req .URL .Path )
61
+ var buf bytes.Buffer
62
+ var m = make (data.Map )
63
+ if err := tofu .Render (& buf , "home.index" , m ); err != nil {
64
+ http .Error (rw , err .Error (), 500 )
65
+ return
66
+ }
67
+ io .Copy (rw , & buf )
68
+ }
69
+
70
+ func staticFileHandler (rw http.ResponseWriter , req * http.Request ) {
71
+ log .Printf ("Access [asset]: %s %s" , req .Method , req .URL .Path )
43
72
http .ServeFile (rw , req , path .Join (* webRoot , req .URL .Path ))
44
73
}
45
74
46
75
func main () {
47
76
flag .Parse ()
48
- http .HandleFunc ("/" , indexHandler )
77
+
78
+ compiledTofu , err := soy .NewBundle ().WatchFiles (true ).AddTemplateDir (* webRoot ).CompileToTofu ()
79
+ if err != nil {
80
+ log .Fatal ("Error compiling Soy templates: " , err .Error ())
81
+ }
82
+ tofu = compiledTofu
83
+
84
+ http .HandleFunc ("/" , dispatchHandler )
49
85
50
86
hostPort := fmt .Sprintf ("%s:%s" , * host , * port )
51
87
log .Printf ("Listening on %s" , hostPort )
0 commit comments