an example of how to embed static assets into a distributable go binary.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

61 lines
1.2 KiB

package web
import (
"fmt"
"net/http"
"path/filepath"
"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
//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": time.Now().Format(time.Stamp),
}
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)
}