Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Embed static files in binary #452

Merged
merged 1 commit into from
Aug 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions handlers/static.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,40 @@
package handlers

import (
"embed"
"io/fs"
"log"
"net/http"
"os"
"path"
"strconv"
"time"
)

//go:embed static
var staticFS embed.FS

// serveStaticResource serves any static file under the ./handlers/static
// directory.
func serveStaticResource() http.HandlerFunc {
const staticRootDir = "./handlers/static"
fs := http.FileServer(http.Dir(staticRootDir))
fSys, err := fs.Sub(staticFS, "static")
if err != nil {
panic(err)
}
server := http.FileServer(http.FS(fSys))

return func(w http.ResponseWriter, r *http.Request) {
// Set cache headers
if mt, ok := lastModTime(path.Join(staticRootDir, r.URL.Path)); ok {
if mt, ok := lastModTime(staticFS, r.URL.Path); ok {
etag := "\"" + strconv.FormatInt(mt.UnixMilli(), 10) + "\""
w.Header().Set("Etag", etag)
w.Header().Set("Cache-Control", "max-age=3600")
}

fs.ServeHTTP(w, r)
server.ServeHTTP(w, r)
}
}

func lastModTime(path string) (time.Time, bool) {
file, err := os.Open(path)
func lastModTime(fs fs.FS, path string) (time.Time, bool) {
file, err := fs.Open(path)
if err != nil {
return time.Time{}, false
}
Expand Down
Loading