don't require knowing the asset paths

This commit is contained in:
sentriz
2019-07-10 10:57:39 +01:00
parent b5aa0ef527
commit 0c5a20c508
8 changed files with 52 additions and 104 deletions

View File

@@ -9,7 +9,7 @@
<body> <body>
<div id="content"> <div id="content">
<div id="header"> <div id="header">
<img src="/admin/static/images/gonic.png"> <img src="/admin/static/gonic.png">
</div> </div>
{{ if .Flashes }} {{ if .Flashes }}
{{ $flash := index .Flashes 0 }} {{ $flash := index .Flashes 0 }}

View File

@@ -1,8 +1,8 @@
{{ define "head" }} {{ define "head" }}
<link rel="stylesheet" href="/admin/static/stylesheets/reset.css"> <link rel="stylesheet" href="/admin/static/reset.css">
<link rel="stylesheet" href="https://cdn.materialdesignicons.com/3.6.95/css/materialdesignicons.min.css"> <link rel="stylesheet" href="https://cdn.materialdesignicons.com/3.6.95/css/materialdesignicons.min.css">
<link rel="stylesheet" href="/admin/static/stylesheets/main.css"> <link rel="stylesheet" href="/admin/static/main.css">
<link rel="shortcut icon" href="/admin/static/images/favicon.ico" type="image/x-icon"> <link rel="shortcut icon" href="/admin/static/favicon.ico" type="image/x-icon">
<link rel="icon" href="/admin/static/images/favicon.ico" type="image/x-icon"> <link rel="icon" href="/admin/static/favicon.ico" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
{{ end }} {{ end }}

View File

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 236 KiB

View File

@@ -1,27 +0,0 @@
package server
import (
"bytes"
"errors"
"io"
"time"
)
var errAssetNotFound = errors.New("asset not found")
func findAsset(path string) (time.Time, io.ReadSeeker, error) {
asset, ok := assetBytes[path]
if !ok {
return time.Time{}, nil, errAssetNotFound
}
reader := bytes.NewReader(asset.Bytes)
return asset.ModTime, reader, nil
}
func findAssetBytes(path string) (time.Time, []byte, error) {
asset, ok := assetBytes[path]
if !ok {
return time.Time{}, nil, errAssetNotFound
}
return asset.ModTime, asset.Bytes, nil
}

View File

@@ -1,81 +1,59 @@
package server package server
import ( import (
"bytes"
"html/template" "html/template"
"log"
"net/http" "net/http"
"path/filepath" "path/filepath"
"strings"
"time" "time"
"github.com/Masterminds/sprig" //nolint:typecheck "github.com/Masterminds/sprig" //nolint:typecheck
"github.com/dustin/go-humanize" "github.com/dustin/go-humanize"
"github.com/gorilla/securecookie" "github.com/gorilla/securecookie"
"github.com/pkg/errors"
"github.com/wader/gormstore" "github.com/wader/gormstore"
) )
var ( const (
partialsPaths = []string{ prefixLayouts = "layouts"
"partials/head.tmpl", prefixPages = "pages"
} prefixPartials = "partials"
layoutPaths = []string{ prefixStatic = "static"
"layouts/base.tmpl",
"layouts/user.tmpl",
}
pagePaths = []string{
"pages/change_own_password.tmpl",
"pages/change_password.tmpl",
"pages/create_user.tmpl",
"pages/delete_user.tmpl",
"pages/home.tmpl",
"pages/login.tmpl",
"pages/update_lastfm_api_key.tmpl",
}
imagePaths = []string{
"images/favicon.ico",
"images/gonic.png",
"images/gone.png",
}
stylesheetPaths = []string{
"stylesheets/main.css",
"stylesheets/reset.css",
}
) )
type templateMap map[string]*template.Template type tmplMap map[string]*template.Template
func parseFromPaths(base *template.Template, paths []string, dest templateMap) error { // prefixDo runs a given callback for every path in our assets with
for _, path := range paths { // the given prefix
_, tmplBytes, err := findAssetBytes(path) func prefixDo(pre string, cb func(path string, asset *EmbeddedAsset)) {
if err != nil { for path, asset := range assetBytes {
return errors.Wrapf(err, "getting template %q from assets", path) if strings.HasPrefix(path, pre) {
cb(path, asset)
} }
tmplStr := string(tmplBytes)
if dest != nil {
// we have a destination. meaning this template is a page.
// instead of parsing as usual, we need to clone and add to the
// template map
clone := template.Must(base.Clone())
tmplKey := filepath.Base(path)
dest[tmplKey] = template.Must(clone.Parse(tmplStr))
continue
}
_ = template.Must(base.Parse(tmplStr))
} }
return nil
} }
func staticHandler(path string) http.HandlerFunc { // extendFromPaths /extends/ the given template for every asset
return func(w http.ResponseWriter, r *http.Request) { // with given prefix
modTime, reader, err := findAsset(path) func extendFromPaths(b *template.Template, p string) *template.Template {
if err != nil { prefixDo(p, func(_ string, asset *EmbeddedAsset) {
log.Printf("error getting file %q from assets: %v\n", path, err) tmplStr := string(asset.Bytes)
http.Redirect(w, r, "/", http.StatusSeeOther) b = template.Must(b.Parse(tmplStr))
return })
} return b
_, name := filepath.Split(path) }
http.ServeContent(w, r, name, modTime, reader)
} // extendFromPaths /clones/ the given template for every asset
// with given prefix, extends it, and insert it into a new tmplMap
func pagesFromPaths(b *template.Template, p string) tmplMap {
ret := tmplMap{}
prefixDo(p, func(path string, asset *EmbeddedAsset) {
tmplKey := filepath.Base(path)
clone := template.Must(b.Clone())
tmplStr := string(asset.Bytes)
ret[tmplKey] = template.Must(clone.Parse(tmplStr))
})
return ret
} }
func (s *Server) SetupAdmin() error { func (s *Server) SetupAdmin() error {
@@ -93,16 +71,18 @@ func (s *Server) SetupAdmin() error {
Funcs(template.FuncMap{ Funcs(template.FuncMap{
"humanDate": humanize.Time, "humanDate": humanize.Time,
}) })
if err := parseFromPaths(tmplBase, partialsPaths, nil); err != nil { tmplBase = extendFromPaths(tmplBase, prefixPartials)
return errors.Wrap(err, "parsing template partials") tmplBase = extendFromPaths(tmplBase, prefixLayouts)
} s.Templates = pagesFromPaths(tmplBase, prefixPages)
if err := parseFromPaths(tmplBase, layoutPaths, nil); err != nil { // setup static server
return errors.Wrap(err, "parsing template layouts") prefixDo(prefixStatic, func(path string, asset *EmbeddedAsset) {
} _, name := filepath.Split(path)
s.Templates = make(templateMap) route := filepath.Join("/admin/static", name)
if err := parseFromPaths(tmplBase, pagePaths, s.Templates); err != nil { reader := bytes.NewReader(asset.Bytes)
return errors.Wrap(err, "parsing template pages for destination") s.mux.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) {
} http.ServeContent(w, r, name, asset.ModTime, reader)
})
})
// //
withPublicWare := newChain( withPublicWare := newChain(
s.WithLogging, s.WithLogging,
@@ -116,11 +96,6 @@ func (s *Server) SetupAdmin() error {
withUserWare, withUserWare,
s.WithAdminSession, s.WithAdminSession,
) )
// begin static server
for _, path := range append(imagePaths, stylesheetPaths...) {
fullPath := filepath.Join("/admin/static", path)
s.mux.HandleFunc(fullPath, staticHandler(path))
}
// begin public routes (creates new session) // begin public routes (creates new session)
s.mux.HandleFunc("/admin/login", withPublicWare(s.ServeLogin)) s.mux.HandleFunc("/admin/login", withPublicWare(s.ServeLogin))
s.mux.HandleFunc("/admin/login_do", withPublicWare(s.ServeLoginDo)) s.mux.HandleFunc("/admin/login_do", withPublicWare(s.ServeLoginDo))