-
Notifications
You must be signed in to change notification settings - Fork 6
/
template.go
61 lines (53 loc) · 1.42 KB
/
template.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
61
package main
import (
"net/http"
"os"
"github.com/goburrow/melon"
"github.com/goburrow/melon/assets"
"github.com/goburrow/melon/core"
"github.com/goburrow/melon/views"
)
const (
templateDir = "./html"
staticPath = "/static/"
)
func index(w http.ResponseWriter, r *http.Request) {
data := struct {
Title string
Name string
StaticPath string
}{
"Melon",
"Gopher",
staticPath,
}
views.Serve(w, r, &data)
}
type app struct{}
func (a *app) Initialize(bs *core.Bootstrap) {
bs.AddBundle(assets.NewBundle(os.TempDir(), staticPath)) // Serve static files
bs.AddBundle(views.NewBundle(views.NewJSONProvider())) // Also support JSON
}
func (a *app) Run(conf interface{}, env *core.Environment) error {
renderer, err := views.NewHTMLRenderer(templateDir, "*.html")
if err != nil {
return err
}
indexPage := views.NewResource("GET", "/", http.HandlerFunc(index),
views.WithHTMLTemplate("index.html"), // HTML template name in ./html folder
views.WithProduces("text/html", "application/json"), // Override priority
)
env.Server.Register(views.NewHTMLProvider(renderer), indexPage)
return nil
}
// Run it:
// $ go run template.go server config.json
//
// Open http://localhost:8080/static/
// Also try this to retrieve the pure json data:
// curl -H'Accept: application/json' 'http://localhost:8080'
func main() {
if err := melon.Run(&app{}, os.Args[1:]); err != nil {
panic(err)
}
}