forked from icereed/paperless-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembedded_assets.go
54 lines (46 loc) · 1.33 KB
/
embedded_assets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"embed"
"io"
"io/fs"
"net/http"
"path"
"strings"
"github.com/gin-gonic/gin"
)
//go:embed web-app/dist/*
var webappContent embed.FS
// CreateEmbeddedFileServer creates a http.FileSystem from our embedded files
func createEmbeddedFileServer() http.FileSystem {
// Strip the "dist" prefix from the embedded files
stripped, err := fs.Sub(webappContent, "web-app/dist")
if err != nil {
panic(err)
}
return http.FS(stripped)
}
// ServeEmbeddedFile serves a file from the embedded filesystem
func serveEmbeddedFile(c *gin.Context, prefix string, filepath string) {
// If the path is empty or ends with "/", serve index.html
if filepath == "" || strings.HasSuffix(filepath, "/") {
filepath = path.Join(filepath, "index.html")
}
// Try to open the file from our embedded filesystem
fullPath := path.Join("web-app/dist", prefix, filepath)
f, err := webappContent.Open(fullPath)
if err != nil {
// If file not found, serve 404
log.Warnf("File not found: %s", fullPath)
http.Error(c.Writer, http.StatusText(http.StatusNotFound), http.StatusNotFound)
c.Status(http.StatusNotFound)
return
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
// Serve the file
http.ServeContent(c.Writer, c.Request, stat.Name(), stat.ModTime(), f.(io.ReadSeeker))
}