Skip to content

Commit

Permalink
refactor(admin): use go1.16 embed for templates and assets
Browse files Browse the repository at this point in the history
  • Loading branch information
sentriz committed May 8, 2021
1 parent 6f15589 commit 0c871d8
Show file tree
Hide file tree
Showing 9 changed files with 78 additions and 11,322 deletions.
2 changes: 1 addition & 1 deletion Dockerfile.dev
Expand Up @@ -12,7 +12,7 @@ WORKDIR /src
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
./_do_build_server
GOOS=linux go build -o gonic cmd/gonic/gonic.go

FROM alpine:3.12.3
RUN apk add -U --no-cache \
Expand Down
22 changes: 0 additions & 22 deletions cmd/gonictag/main.go

This file was deleted.

11,232 changes: 0 additions & 11,232 deletions server/assets/assets.gen.go

This file was deleted.

23 changes: 13 additions & 10 deletions server/assets/assets.go
@@ -1,15 +1,18 @@
//nolint:gochecknoglobals,golint,stylecheck
package assets

import (
"strings"
"embed"
)

// PrefixDo runs a given callback for every path in our assets with
// the given prefix
func PrefixDo(pre string, cb func(path string, asset *EmbeddedAsset)) {
for path, asset := range Bytes {
if strings.HasPrefix(path, pre) {
cb(path, asset)
}
}
}
//go:embed layouts
var Layouts embed.FS

//go:embed pages
var Pages embed.FS

//go:embed partials
var Partials embed.FS

//go:embed static
var Static embed.FS
73 changes: 35 additions & 38 deletions server/ctrladmin/ctrl.go
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
"net/url"
Expand All @@ -19,11 +20,11 @@ import (
"github.com/oxtoacart/bpool"
"github.com/wader/gormstore"

"go.senan.xyz/gonic"
"go.senan.xyz/gonic/server/assets"
"go.senan.xyz/gonic/server/ctrlbase"
"go.senan.xyz/gonic/server/db"
"go.senan.xyz/gonic/server/podcasts"
"go.senan.xyz/gonic/version"
)

type CtxKey int
Expand All @@ -33,41 +34,12 @@ const (
CtxSession
)

// extendFromPaths /extends/ the given template for every asset
// with given prefix
func extendFromPaths(b *template.Template, p string) *template.Template {
assets.PrefixDo(p, func(_ string, asset *assets.EmbeddedAsset) {
tmplStr := string(asset.Bytes)
b = template.Must(b.Parse(tmplStr))
})
return b
}

// extendFromPaths /clones/ the given template for every asset
// with given prefix, extends it, and insert it into a new map
func pagesFromPaths(b *template.Template, p string) map[string]*template.Template {
ret := map[string]*template.Template{}
assets.PrefixDo(p, func(path string, asset *assets.EmbeddedAsset) {
tmplKey := filepath.Base(path)
clone := template.Must(b.Clone())
tmplStr := string(asset.Bytes)
ret[tmplKey] = template.Must(clone.Parse(tmplStr))
})
return ret
}

const (
prefixPartials = "partials"
prefixLayouts = "layouts"
prefixPages = "pages"
)

func funcMap() template.FuncMap {
return template.FuncMap{
"noCache": func(in string) string {
parsed, _ := url.Parse(in)
params := parsed.Query()
params.Set("v", version.VERSION)
params.Set("v", gonic.Version)
parsed.RawQuery = params.Encode()
return parsed.String()
},
Expand All @@ -86,23 +58,45 @@ type Controller struct {
Podcasts *podcasts.Podcasts
}

func New(b *ctrlbase.Controller, sessDB *gormstore.Store, podcasts *podcasts.Podcasts) *Controller {
tmplBase := template.
func New(b *ctrlbase.Controller, sessDB *gormstore.Store, podcasts *podcasts.Podcasts) (*Controller, error) {
tmpl := template.
New("layout").
Funcs(sprig.FuncMap()).
Funcs(funcMap()). // static
Funcs(template.FuncMap{ // from base
"path": b.Path,
})
tmplBase = extendFromPaths(tmplBase, prefixPartials)
tmplBase = extendFromPaths(tmplBase, prefixLayouts)

var err error
tmpl, err = tmpl.ParseFS(assets.Partials, "**/*.tmpl")
if err != nil {
return nil, fmt.Errorf("extend partials: %w", err)
}
tmpl, err = tmpl.ParseFS(assets.Layouts, "**/*.tmpl")
if err != nil {
return nil, fmt.Errorf("extend layouts: %w", err)
}

pagePaths, err := fs.Glob(assets.Pages, "**/*.tmpl")
if err != nil {
return nil, fmt.Errorf("parse pages: %w", err)
}
pages := map[string]*template.Template{}
for _, pagePath := range pagePaths {
pageBytes, _ := assets.Pages.ReadFile(pagePath)
page, _ := tmpl.Clone()
page, _ = page.Parse(string(pageBytes))
pageName := filepath.Base(pagePath)
pages[pageName] = page
}

return &Controller{
Controller: b,
buffPool: bpool.NewBufferPool(64),
templates: pagesFromPaths(tmplBase, prefixPages),
templates: pages,
sessDB: sessDB,
Podcasts: podcasts,
}
}, nil
}

type templateData struct {
Expand Down Expand Up @@ -178,10 +172,11 @@ func (c *Controller) H(h handlerAdmin) http.Handler {
http.Error(w, "useless handler return", 500)
return
}

if resp.data == nil {
resp.data = &templateData{}
}
resp.data.Version = version.VERSION
resp.data.Version = gonic.Version
if session != nil {
resp.data.Flashes = session.Flashes()
if err := session.Save(r, w); err != nil {
Expand All @@ -192,6 +187,7 @@ func (c *Controller) H(h handlerAdmin) http.Handler {
if user, ok := r.Context().Value(CtxUser).(*db.User); ok {
resp.data.User = user
}

buff := c.buffPool.Get()
defer c.buffPool.Put(buff)
tmpl, ok := c.templates[resp.template]
Expand All @@ -203,6 +199,7 @@ func (c *Controller) H(h handlerAdmin) http.Handler {
http.Error(w, fmt.Sprintf("executing template: %v", err), 500)
return
}

w.Header().Set("Content-Type", "text/html; charset=utf-8")
if resp.code != 0 {
w.WriteHeader(resp.code)
Expand Down
4 changes: 2 additions & 2 deletions server/ctrladmin/middleware.go
Expand Up @@ -7,13 +7,13 @@ import (

"github.com/gorilla/sessions"

"go.senan.xyz/gonic"
"go.senan.xyz/gonic/server/db"
"go.senan.xyz/gonic/version"
)

func (c *Controller) WithSession(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := c.sessDB.Get(r, version.NAME)
session, err := c.sessDB.Get(r, gonic.Name)
if err != nil {
http.Error(w, fmt.Sprintf("error getting session: %s", err), 500)
return
Expand Down
10 changes: 5 additions & 5 deletions server/ctrlsubsonic/spec/spec.go
Expand Up @@ -4,8 +4,8 @@ import (
"fmt"
"time"

"go.senan.xyz/gonic"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
"go.senan.xyz/gonic/version"
)

const (
Expand Down Expand Up @@ -53,8 +53,8 @@ func NewResponse() *Response {
Status: "ok",
XMLNS: xmlns,
Version: apiVersion,
Type: version.NAME,
GonicVersion: version.VERSION,
Type: gonic.Name,
GonicVersion: gonic.Version,
}
}

Expand Down Expand Up @@ -82,8 +82,8 @@ func NewError(code int, message string, a ...interface{}) *Response {
Code: code,
Message: fmt.Sprintf(message, a...),
},
Type: version.NAME,
GonicVersion: version.VERSION,
Type: gonic.Name,
GonicVersion: gonic.Version,
}
}

Expand Down
31 changes: 19 additions & 12 deletions server/server.go
@@ -1,7 +1,6 @@
package server

import (
"bytes"
"fmt"
"log"
"net/http"
Expand Down Expand Up @@ -44,7 +43,7 @@ type Server struct {
podcast *podcasts.Podcasts
}

func New(opts Options) *Server {
func New(opts Options) (*Server, error) {
opts.MusicPath = filepath.Clean(opts.MusicPath)
opts.CachePath = filepath.Clean(opts.CachePath)
opts.PodcastPath = filepath.Clean(opts.PodcastPath)
Expand All @@ -70,7 +69,11 @@ func New(opts Options) *Server {
sessDB.SessionOpts.SameSite = http.SameSiteLaxMode

podcast := &podcasts.Podcasts{DB: opts.DB, PodcastBasePath: opts.PodcastPath}
ctrlAdmin := ctrladmin.New(base, sessDB, podcast)

ctrlAdmin, err := ctrladmin.New(base, sessDB, podcast)
if err != nil {
return nil, fmt.Errorf("create admin controller: %w", err)
}
ctrlSubsonic := &ctrlsubsonic.Controller{
Controller: base,
CachePath: opts.CachePath,
Expand Down Expand Up @@ -99,7 +102,7 @@ func New(opts Options) *Server {
server.jukebox = jukebox
}

return server
return server, nil
}

func setupMisc(r *mux.Router, ctrl *ctrlbase.Controller) {
Expand All @@ -124,14 +127,10 @@ func setupAdmin(r *mux.Router, ctrl *ctrladmin.Controller) {
r.Use(ctrl.WithSession)
r.Handle("/login", ctrl.H(ctrl.ServeLogin))
r.Handle("/login_do", ctrl.HR(ctrl.ServeLoginDo)) // "raw" handler, updates session
assets.PrefixDo("static", func(path string, asset *assets.EmbeddedAsset) {
_, name := filepath.Split(path)
route := filepath.Join("/static", name)
reader := bytes.NewReader(asset.Bytes)
r.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) {
http.ServeContent(w, r, name, asset.ModTime, reader)
})
})

staticHandler := http.StripPrefix("/admin", http.FileServer(http.FS(assets.Static)))
r.PathPrefix("/static").Handler(staticHandler)

// ** begin user routes (if session is valid)
routUser := r.NewRoute().Subrouter()
routUser.Use(ctrl.WithUserSession)
Expand All @@ -153,6 +152,7 @@ func setupAdmin(r *mux.Router, ctrl *ctrladmin.Controller) {
routUser.Handle("/delete_podcast_do", ctrl.H(ctrl.ServePodcastDeleteDo))
routUser.Handle("/download_podcast_do", ctrl.H(ctrl.ServePodcastDownloadDo))
routUser.Handle("/update_podcast_do", ctrl.H(ctrl.ServePodcastUpdateDo))

// ** begin admin routes (if session is valid, and is admin)
routAdmin := routUser.NewRoute().Subrouter()
routAdmin.Use(ctrl.WithAdminSession)
Expand All @@ -168,6 +168,7 @@ func setupAdmin(r *mux.Router, ctrl *ctrladmin.Controller) {
routAdmin.Handle("/update_lastfm_api_key_do", ctrl.H(ctrl.ServeUpdateLastFMAPIKeyDo))
routAdmin.Handle("/start_scan_inc_do", ctrl.H(ctrl.ServeStartScanIncDo))
routAdmin.Handle("/start_scan_full_do", ctrl.H(ctrl.ServeStartScanFullDo))

// middlewares should be run for not found handler
// https://github.com/gorilla/mux/issues/416
notFoundHandler := ctrl.H(ctrl.ServeNotFound)
Expand All @@ -179,6 +180,7 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
r.Use(ctrl.WithParams)
r.Use(ctrl.WithRequiredParams)
r.Use(ctrl.WithUser)

// ** begin common
r.Handle("/getLicense{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetLicence))
r.Handle("/getMusicFolders{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetMusicFolders))
Expand All @@ -201,31 +203,36 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
r.Handle("/getBookmarks{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetBookmarks))
r.Handle("/createBookmark{_:(?:\\.view)?}", ctrl.H(ctrl.ServeCreateBookmark))
r.Handle("/deleteBookmark{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeleteBookmark))

// ** begin raw
r.Handle("/download{_:(?:\\.view)?}", ctrl.HR(ctrl.ServeDownload))
r.Handle("/getCoverArt{_:(?:\\.view)?}", ctrl.HR(ctrl.ServeGetCoverArt))
r.Handle("/stream{_:(?:\\.view)?}", ctrl.HR(ctrl.ServeStream))

// ** begin browse by tag
r.Handle("/getAlbum{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetAlbum))
r.Handle("/getAlbumList2{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetAlbumListTwo))
r.Handle("/getArtist{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtist))
r.Handle("/getArtists{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtists))
r.Handle("/search3{_:(?:\\.view)?}", ctrl.H(ctrl.ServeSearchThree))
r.Handle("/getArtistInfo2{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtistInfoTwo))

// ** begin browse by folder
r.Handle("/getIndexes{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetIndexes))
r.Handle("/getMusicDirectory{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetMusicDirectory))
r.Handle("/getAlbumList{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetAlbumList))
r.Handle("/search2{_:(?:\\.view)?}", ctrl.H(ctrl.ServeSearchTwo))
r.Handle("/getGenres{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetGenres))
r.Handle("/getArtistInfo{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtistInfo))

// ** begin podcasts
r.Handle("/getPodcasts{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetPodcasts))
r.Handle("/downloadPodcastEpisode{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDownloadPodcastEpisode))
r.Handle("/createPodcastChannel{_:(?:\\.view)?}", ctrl.H(ctrl.ServeCreatePodcastChannel))
r.Handle("/refreshPodcasts{_:(?:\\.view)?}", ctrl.H(ctrl.ServeRefreshPodcasts))
r.Handle("/deletePodcastChannel{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeletePodcastChannel))
r.Handle("/deletePodcastEpisode{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeletePodcastEpisode))

// middlewares should be run for not found handler
// https://github.com/gorilla/mux/issues/416
notFoundHandler := ctrl.H(ctrl.ServeNotFound)
Expand Down
3 changes: 3 additions & 0 deletions version.go
Expand Up @@ -7,3 +7,6 @@ import (

//go:embed version.txt
var Version string

const Name = "gonic"
const NameUpper = "GONIC"

0 comments on commit 0c871d8

Please sign in to comment.