-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathembed_prod.go
53 lines (43 loc) · 1.15 KB
/
embed_prod.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
// embed_prod.go
//go:build production
package main
import (
"embed"
"io"
"io/fs"
"net/http"
"time"
"github.com/labstack/echo/v5"
)
//go:embed dist/*
var distFS embed.FS
// ServeViteAssets serves the embedded Vite assets in production
func ServeViteAssets(e *echo.Echo) {
fsys, err := fs.Sub(distFS, "dist")
if err != nil {
println("Failed to get filesystem:", err.Error())
return
}
fileServer := http.FileServer(http.FS(fsys))
e.Any("/*", func(c echo.Context) error {
path := c.PathParam("*")
// Check if the file exists
if path != "" {
if _, err := fsys.Open(path); err == nil {
// File exists, serve it directly
fileServer.ServeHTTP(c.Response().Writer, c.Request())
return nil
}
}
// If no file is found or path is empty, serve index.html
c.Response().Header().Set("Content-Type", "text/html")
indexFile, err := fsys.Open("index.html")
if err != nil {
println("Failed to open index.html:", err.Error())
return echo.NewHTTPError(http.StatusNotFound)
}
defer indexFile.Close()
http.ServeContent(c.Response().Writer, c.Request(), "index.html", time.Now(), indexFile.(io.ReadSeeker))
return nil
})
}