Skip to content
Permalink
Browse files

Rework static folder, save items inside their parent folders

  • Loading branch information...
Raggaer committed Apr 1, 2019
1 parent 43f2976 commit 17a674d68b91cb6855d1d63034212c54e6ac3df6
Showing with 26 additions and 14 deletions.
  1. +26 −14 static.go
@@ -4,6 +4,7 @@ import (
"bytes"
"compress/gzip"
"io"
"log"
"net/http"
"os"
"path/filepath"
@@ -67,31 +68,30 @@ func ServeStaticFiles(c *gin.Context) {
for _, asset := range AssetMap.Assets {
if asset.Name == filepath.Join("static", p) {
c.Header("Etag", asset.Hash)
break
c.File(filepath.Join("static", p))
return
}
}

c.File(filepath.Join("static", p))
c.Status(http.StatusNotFound)
}

// LoadStaticAssets generates static content from the given directory
func LoadStaticAssets(dir string) error {
// Create static directory again
os.RemoveAll("static")
if err := os.Mkdir("static", 0755); err != nil {
return err
}

minifier := minify.New()
minifier.AddFunc("text/css", css.Minify)
minifier.AddFunc("text/js", js.Minify)
AssetMap.rw.Lock()
i := 0
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || strings.HasSuffix(path, "~") {
if info.IsDir() {
dirPath := buildNewPath(dir, filepath.Join("static", path))
if err := os.Mkdir(dirPath, 0755); err != nil {
log.Println(err, dirPath)
return err
}
return nil
}

@@ -103,11 +103,13 @@ func LoadStaticAssets(dir string) error {
strings.HasSuffix(path, ".svg") ||
strings.HasSuffix(path, ".jpg") ||
strings.HasSuffix(path, ".gif") {
fname = filepath.Join("static", strconv.Itoa(i)+"_"+info.Name())
fname = buildNewPath(dir, filepath.Join("static", path))
} else {
fname = filepath.Join("static", strconv.FormatInt(info.ModTime().Unix(), 10)+"_"+info.Name()+".gz")
fname = buildNewPath(dir, filepath.Join("static", filepath.Dir(path), strconv.FormatInt(info.ModTime().Unix(), 10)+"_"+info.Name()+".gz"))
}

log.Println(fname)

dst, err := os.OpenFile(fname, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0777)
if err != nil {
return err
@@ -148,7 +150,6 @@ func LoadStaticAssets(dir string) error {
}
dst.Close()
src.Close()
i++
return nil
}

@@ -165,7 +166,6 @@ func LoadStaticAssets(dir string) error {
}
dst.Close()
src.Close()
i++
return nil
})
AssetMap.rw.Unlock()
@@ -183,3 +183,15 @@ func Asset(path string) string {
}
return "/" + filepath.ToSlash(v.Name)
}

func buildNewPath(base, path string) string {
ret := []string{}
p := strings.Split(path, string(os.PathSeparator))
for _, path := range p {
if path == base {
continue
}
ret = append(ret, path)
}
return strings.Join(ret, string(os.PathSeparator))
}

0 comments on commit 17a674d

Please sign in to comment.
You can’t perform that action at this time.