38 lines
959 B
Go
38 lines
959 B
Go
package router
|
|
|
|
import (
|
|
"bytes"
|
|
"io/fs"
|
|
"net/http"
|
|
"path"
|
|
"time"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
// FileHandler handles loading file assets
|
|
func (re *Router) FileHandler(ph string) HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) error {
|
|
filename := mux.Vars(r)["filename"]
|
|
file, err := fs.ReadFile(re.fsys, "assets/"+ph+"/"+filename)
|
|
if err != nil {
|
|
return HTTPError(http.StatusNotFound, err)
|
|
}
|
|
switch p := path.Ext(filename); p {
|
|
case ".css":
|
|
w.Header().Set("Content-Type", "text/css")
|
|
case ".js":
|
|
w.Header().Set("Content-Type", "application/javascript")
|
|
case ".json":
|
|
w.Header().Set("Content-Type", "application/json")
|
|
case ".svg":
|
|
w.Header().Set("Content-Type", "image/svg+xml")
|
|
default:
|
|
w.Header().Set("Content-Type", http.DetectContentType(file))
|
|
}
|
|
w.Header().Set("Cache-Control", "max-age=2592000")
|
|
http.ServeContent(w, r, filename, time.Now(), bytes.NewReader(file))
|
|
return nil
|
|
}
|
|
}
|