GoBlog/media.go

27 lines
566 B
Go
Raw Normal View History

2021-01-10 14:59:43 +00:00
package main
import (
"net/http"
"os"
"path/filepath"
2021-03-03 17:19:55 +00:00
"github.com/go-chi/chi/v5"
2021-01-10 14:59:43 +00:00
)
const (
mediaFilePath = "data/media"
mediaFileRoute = `/{file:[0-9a-fA-F]+(\.[0-9a-zA-Z]+)?}`
)
2021-01-10 14:59:43 +00:00
2022-02-25 15:29:42 +00:00
func (*goBlog) serveMediaFile(w http.ResponseWriter, r *http.Request) {
2021-01-10 14:59:43 +00:00
f := filepath.Join(mediaFilePath, chi.URLParam(r, "file"))
_, err := os.Stat(f)
if err != nil {
// Serve 404, but don't use normal serve404 method because of media domain
http.NotFound(w, r)
2021-01-10 14:59:43 +00:00
return
}
2022-02-01 14:58:12 +00:00
w.Header().Add(cacheControl, "public,max-age=31536000,immutable")
2021-01-10 14:59:43 +00:00
http.ServeFile(w, r, f)
}