Skip to content

Commit

Permalink
use net/http serve static file
Browse files Browse the repository at this point in the history
  • Loading branch information
Arvintian committed Jul 22, 2022
1 parent 4410ace commit 5e646ac
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 57 deletions.
63 changes: 9 additions & 54 deletions internal/admin/handlers/assets.go
Original file line number Diff line number Diff line change
@@ -1,64 +1,19 @@
package handlers

import (
"bufio"
"io"
"net/http"
"path"
"regexp"
"strings"
)

var assetsPath = "web/assets/"
var (
jsRe = regexp.MustCompile(`^/assets/(js/.*)?.*$`)
cssRe = regexp.MustCompile(`^/assets/(css/.*)?.*$`)
fontRe = regexp.MustCompile(`/([^/]*)?.*$`)
)

type AssetType int

const (
AssetTypeJs AssetType = iota
AssetTypeCss
AssetTypeFont
)

func HandleGetAssets(assetType AssetType) http.HandlerFunc {
func HandleGetAssets(pathPrefix string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var m = ""
switch assetType {
case AssetTypeJs:
m = getMatch(r, jsRe)
w.Header().Set("Content-Type", "application/javascript")
case AssetTypeCss:
m = getMatch(r, cssRe)
w.Header().Set("Content-Type", "text/css")
case AssetTypeFont:
m = getMatch(r, fontRe)
m = path.Join("fonts", m)
w.Header().Set("Content-Type", "application/font-woff2")
}
if m == "" {
http.NotFound(w, r)
return
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
f, err := assets.Open(path.Join(assetsPath, m))
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
_, err = io.Copy(w, bufio.NewReader(f))
if err != nil {
encodeError(w, err)
}
}
}

func getMatch(r *http.Request, re *regexp.Regexp) string {
m := re.FindStringSubmatch(r.URL.Path)
if len(m) > 1 {
return m[1]
r.URL.Path = pathPrefix + r.URL.Path
w.Header().Set("Cache-Control", "max-age=86400")
http.FileServer(http.FS(assets)).ServeHTTP(w, r)
}
return ""
}
6 changes: 3 additions & 3 deletions internal/admin/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ func defaultRoutes(cfg *Config) []*route {
WkDir: cfg.WorkDir,
},
)},
{http.MethodGet, `^/assets/js/.*$`, handlers.HandleGetAssets(handlers.AssetTypeJs)},
{http.MethodGet, `^/assets/css/.*$`, handlers.HandleGetAssets(handlers.AssetTypeCss)},
{http.MethodGet, `^*.woff2$|^*.ttf$`, handlers.HandleGetAssets(handlers.AssetTypeFont)},
{http.MethodGet, `^/assets/js/.*$`, handlers.HandleGetAssets("/web")},
{http.MethodGet, `^/assets/css/.*$`, handlers.HandleGetAssets("/web")},
{http.MethodGet, `^*.woff2$|^*.ttf$`, handlers.HandleGetAssets("/web/assets/fonts")},
}
}

0 comments on commit 5e646ac

Please sign in to comment.