refactor asset with embed tool

This commit is contained in:
sentriz
2019-06-26 12:01:49 +01:00
parent e6c6d2406f
commit d8881bd31c
35 changed files with 11004 additions and 21662 deletions

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 236 KiB

View File

@@ -4,12 +4,7 @@
<head>
<meta charset="utf-8">
<title>gonic</title>
<link rel="stylesheet" href="/admin/static/stylesheets/reset.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="shortcut icon" href="/admin/static/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="/admin/static/images/favicon.ico" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
{{ template "head" }}
</head>
<body>
<div>

View File

@@ -0,0 +1,8 @@
{{ define "head" }}
<link rel="stylesheet" href="/admin/static/stylesheets/reset.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="shortcut icon" href="/admin/static/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="/admin/static/images/favicon.ico" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
{{ end }}

10652
server/assets_bytes.go Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
// +build !embed
package server
import "github.com/omeid/go-resources/live"
var (
assets = live.Dir("./assets_src")
)

9
server/assets_getters.go Normal file
View File

@@ -0,0 +1,9 @@
package server
import "errors"
var ErrAssetNotFound = errors.New("asset not found")
type Assets struct {
BasePath string
}

View File

@@ -0,0 +1,39 @@
// +build !embed
package server
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/pkg/errors"
)
func (a *Assets) Find(path string) (time.Time, io.ReadSeeker, error) {
fullPath := filepath.Join(a.BasePath, path)
info, err := os.Stat(fullPath)
if err != nil {
return time.Time{}, nil, errors.Wrap(err, "statting asset")
}
file, err := os.Open(fullPath)
if err != nil {
return time.Time{}, nil, errors.Wrapf(ErrAssetNotFound, "%v", err)
}
return info.ModTime(), file, nil
}
func (a *Assets) FindBytes(path string) (time.Time, []byte, error) {
fullPath := filepath.Join(a.BasePath, path)
info, err := os.Stat(fullPath)
if err != nil {
return time.Time{}, nil, errors.Wrap(err, "statting asset")
}
file, err := ioutil.ReadFile(fullPath)
if err != nil {
return time.Time{}, nil, errors.Wrapf(ErrAssetNotFound, "%v", err)
}
return info.ModTime(), file, nil
}

View File

@@ -0,0 +1,26 @@
// +build embed
package server
import (
"bytes"
"io"
"time"
)
func (_ *Assets) Find(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 (_ *Assets) FindBytes(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,9 +0,0 @@
// +build embed
package server
import "github.com/sentriz/gonic/server/assets_compiled"
var (
assets = assets_compiled.Assets
)

View File

@@ -1,10 +0,0 @@
{{ define "box" }}
<div class="padded box mono">
<div class="box-title">
<i class="mdi mdi-chart-arc"></i> {{ .Title }}
</div>
<div class="block-right">
{{ .Content }}
</div>
</div>
{{ end }}

View File

@@ -24,12 +24,18 @@ func newChain(wares ...middleware) middleware {
}
type Server struct {
mux *http.ServeMux
mux *http.ServeMux
assets *Assets
*handler.Controller
*http.Server
}
func New(db *gorm.DB, musicPath string, listenAddr string) *Server {
func New(
db *gorm.DB,
musicPath string,
listenAddr string,
assetPath string,
) *Server {
mux := http.NewServeMux()
server := &http.Server{
Addr: listenAddr,
@@ -42,8 +48,12 @@ func New(db *gorm.DB, musicPath string, listenAddr string) *Server {
DB: db,
MusicPath: musicPath,
}
assets := &Assets{
BasePath: assetPath,
}
return &Server{
mux: mux,
assets: assets,
Server: server,
Controller: controller,
}

View File

@@ -1,8 +1,8 @@
package server
import (
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
"time"
@@ -11,11 +11,74 @@ import (
"github.com/dustin/go-humanize"
"github.com/gorilla/securecookie"
"github.com/pkg/errors"
"github.com/shurcooL/httpfs/html/vfstemplate"
"github.com/shurcooL/httpfs/path/vfspath"
"github.com/wader/gormstore"
)
var (
partialsPaths = []string{
"partials/box.tmpl",
}
layoutPaths = []string{
"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
func parseFromPaths(assets *Assets, base *template.Template,
paths []string, destination templateMap) error {
for _, path := range paths {
_, tmplBytes, err := assets.FindBytes(path)
if err != nil {
return errors.Wrapf(err, "getting template %q from assets", path)
}
tmplStr := string(tmplBytes)
if destination != 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)
destination[tmplKey] = template.Must(clone.Parse(tmplStr))
continue
}
_ = template.Must(base.Parse(tmplStr))
}
return nil
}
func staticHandler(assets *Assets, path string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
modTime, reader, err := assets.Find(path)
if err != nil {
log.Printf("error getting file %q from assets: %v\n", path, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
_, name := filepath.Split(path)
http.ServeContent(w, r, name, modTime, reader)
}
}
func (s *Server) SetupAdmin() error {
sessionKey := []byte(s.GetSetting("session_key"))
if len(sessionKey) == 0 {
@@ -31,34 +94,18 @@ func (s *Server) SetupAdmin() error {
Funcs(template.FuncMap{
"humanDate": humanize.Time,
})
const (
layoutDir = "/templates/layouts/*"
partialDir = "/templates/partials/*"
pageDir = "/templates/pages/*"
)
tmplLayouts, err := vfstemplate.ParseGlob(assets, tmplBase, layoutDir)
if err != nil {
return errors.Wrap(err, "parsing layouts")
if err := parseFromPaths(
s.assets, tmplBase, partialsPaths, nil); err != nil {
return errors.Wrap(err, "parsing template partials")
}
tmplPartials, err := vfstemplate.ParseGlob(assets, tmplLayouts, partialDir)
if err != nil {
return errors.Wrap(err, "parsing partials")
if err := parseFromPaths(
s.assets, tmplBase, layoutPaths, nil); err != nil {
return errors.Wrap(err, "parsing template layouts")
}
pages, err := vfspath.Glob(assets, pageDir)
if err != nil {
return errors.Wrap(err, "parsing pages")
}
s.Templates = make(map[string]*template.Template)
for _, page := range pages {
tmplStr, ok := assets.String(page)
if !ok {
return fmt.Errorf("getting template %q from assets: %v\n", page)
}
tmplBaseClone := template.Must(tmplPartials.Clone())
tmplWithPage := template.Must(tmplBaseClone.Parse(tmplStr))
tmplWithPartial := template.Must(tmplWithPage.Parse(tmplStr))
shortName := filepath.Base(page)
s.Templates[shortName] = tmplWithPartial
s.Templates = make(templateMap)
if err := parseFromPaths(
s.assets, tmplBase, pagePaths, s.Templates); err != nil {
return errors.Wrap(err, "parsing template pages for destination")
}
//
withPublicWare := newChain(
@@ -74,9 +121,10 @@ func (s *Server) SetupAdmin() error {
s.WithAdminSession,
)
// begin static server
s.mux.Handle("/admin/static/", http.StripPrefix("/admin",
http.FileServer(assets),
))
for _, path := range append(imagePaths, stylesheetPaths...) {
fullPath := filepath.Join("/admin/static", path)
s.mux.HandleFunc(fullPath, staticHandler(s.assets, path))
}
// begin public routes (creates new session)
s.mux.HandleFunc("/admin/login", withPublicWare(s.ServeLogin))
s.mux.HandleFunc("/admin/login_do", withPublicWare(s.ServeLoginDo))