web/web.go

61 lines
1.1 KiB
Go

package web
import (
"fmt"
"net/http"
"path/filepath"
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
//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,
}
}
s.tmpl = NewAssetTemplate(Asset)
if templates != "" {
s.tmpl = Disk{templates}
}
sm.HandleFunc("/", s.Home)
sm.Handle(
"/static/",
http.FileServer(fs),
)
return s
}
func (s *Site) Home(w http.ResponseWriter, req *http.Request) {
c := map[string]string{
"time": "asdf",
}
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)
}