Skip to content

Commit

Permalink
minify html templates on first load
Browse files Browse the repository at this point in the history
  • Loading branch information
pk910 committed Aug 1, 2023
1 parent 55142ae commit 7e2d41e
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 2 deletions.
6 changes: 5 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ require (
gopkg.in/yaml.v3 v3.0.1
)

require github.com/mitchellh/mapstructure v1.5.0 // indirect
require (
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/tdewolff/minify v2.3.6+incompatible // indirect
github.com/tdewolff/parse v2.3.4+incompatible // indirect
)

require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/tdewolff/minify v2.3.6+incompatible h1:2hw5/9ZvxhWLvBUnHE06gElGYz+Jv9R4Eys0XUzItYo=
github.com/tdewolff/minify v2.3.6+incompatible/go.mod h1:9Ov578KJUmAWpS6NeZwRZyT56Uf6o3Mcz9CEsg8USYs=
github.com/tdewolff/parse v2.3.4+incompatible h1:x05/cnGwIMf4ceLuDMBOdQ1qGniMoxpP46ghf0Qzh38=
github.com/tdewolff/parse v2.3.4+incompatible/go.mod h1:8oBwCsVmUkgHO8M5iCzSIDtpzXOT0WXX9cWhz+bIzJQ=
github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc=
github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
Expand Down
72 changes: 71 additions & 1 deletion templates/templates.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
package templates

import (
"bufio"
"embed"
"fmt"
"html/template"
"io"
"io/fs"
"path"
"path/filepath"
"regexp"
"strings"
"sync"

"github.com/sirupsen/logrus"
"github.com/tdewolff/minify"

"github.com/pk910/light-beaconchain-explorer/utils"
)
Expand Down Expand Up @@ -51,13 +56,78 @@ func GetTemplate(files ...string) *template.Template {
}
templateCacheMux.RUnlock()

tmpl := template.Must(template.New(name).Funcs(template.FuncMap(templateFuncs)).ParseFS(Files, files...))
tmpl := template.New(name).Funcs(template.FuncMap(templateFuncs))
tmpl = template.Must(parseTemplateFiles(tmpl, readFileFS(Files), files...))
templateCacheMux.Lock()
defer templateCacheMux.Unlock()
templateCache[name] = tmpl
return templateCache[name]
}

func readFileFS(fsys fs.FS) func(string) (string, []byte, error) {
return func(file string) (name string, b []byte, err error) {
name = path.Base(file)
b, err = fs.ReadFile(fsys, file)

if utils.Config.Frontend.Minify {
// minfiy template
m := minify.New()
m.AddFunc("text/html", minifyTemplate)
b, err = m.Bytes("text/html", b)
if err != nil {
panic(err)
}
}
return
}
}

func minifyTemplate(m *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
// remove newlines and spaces
m1 := regexp.MustCompile(`([ \t]+)?[\r\n]+`)
m2 := regexp.MustCompile(`([ \t])[ \t]+`)
rb := bufio.NewReader(r)
for {
line, err := rb.ReadString('\n')
if err != nil && err != io.EOF {
return err
}
line = m1.ReplaceAllString(line, "")
line = m2.ReplaceAllString(line, " ")
if _, errws := io.WriteString(w, line); errws != nil {
return errws
}
if err == io.EOF {
break
}
}
return nil
}

func parseTemplateFiles(t *template.Template, readFile func(string) (string, []byte, error), filenames ...string) (*template.Template, error) {
for _, filename := range filenames {
name, b, err := readFile(filename)
if err != nil {
return nil, err
}
s := string(b)
var tmpl *template.Template
if t == nil {
t = template.New(name)
}
if name == t.Name() {
tmpl = t
} else {
tmpl = t.New(name)
}
_, err = tmpl.Parse(s)
if err != nil {
return nil, err
}
}
return t, nil
}

func GetTemplateNames() []string {
files, _ := getFileSysNames(fs.FS(Files), ".")
return files
Expand Down
1 change: 1 addition & 0 deletions types/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Config struct {
Frontend struct {
Enabled bool `yaml:"enabled" envconfig:"FRONTEND_ENABLED"`
Debug bool `yaml:"debug" envconfig:"FRONTEND_DEBUG"`
Minify bool `yaml:"minify" envconfig:"FRONTEND_MINIFY"`

SiteDomain string `yaml:"siteDomain" envconfig:"FRONTEND_SITE_DOMAIN"`
SiteName string `yaml:"siteName" envconfig:"FRONTEND_SITE_NAME"`
Expand Down

0 comments on commit 7e2d41e

Please sign in to comment.