web/web.go

62 lines
1.2 KiB
Go
Raw Permalink Normal View History

package web
import (
2017-01-26 19:44:31 -08:00
"fmt"
"net/http"
"path/filepath"
2017-01-26 20:15:18 -08:00
"time"
assetfs "github.com/elazarl/go-bindata-assetfs"
)
//go:generate go get github.com/jteeuwen/go-bindata/...
//go:generate go get github.com/elazarl/go-bindata-assetfs/...
//go:generate rm -f static.go
2017-01-26 19:44:31 -08:00
//go:generate go-bindata -o static.go -pkg=web static/... templates/...
type Site struct {
tmpl TemplateGetter
}
func NewSite(sm *http.ServeMux, static, templates string) *Site {
s := &Site{}
var fs http.FileSystem
if p, d := filepath.Split(static); d == "static" {
static = p
}
fs = http.Dir(static)
if static == "" {
fs = &assetfs.AssetFS{
Asset: Asset,
AssetDir: AssetDir,
AssetInfo: AssetInfo,
}
}
2017-01-26 19:52:34 -08:00
s.tmpl = NewAssetTemplate(Asset)
2017-01-26 19:44:31 -08:00
if templates != "" {
s.tmpl = Disk{templates}
}
sm.HandleFunc("/", s.Home)
sm.Handle(
2017-01-26 19:44:31 -08:00
"/static/",
http.FileServer(fs),
)
2017-01-26 19:44:31 -08:00
return s
}
func (s *Site) Home(w http.ResponseWriter, req *http.Request) {
c := map[string]string{
2017-01-26 20:15:18 -08:00
"time": time.Now().Format(time.Stamp),
2017-01-26 19:44:31 -08:00
}
tmpl, err := s.tmpl.Get("home")
if err != nil {
http.Error(w, fmt.Sprintf("not found: %v", err), http.StatusNotFound)
return
}
tmpl.ExecuteTemplate(w, "base", c)
}