|
| 1 | +package httpapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "embed" |
| 5 | + "fmt" |
| 6 | + "io/fs" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +//go:embed chat/* |
| 13 | +var chatStaticFiles embed.FS |
| 14 | + |
| 15 | +// FileServerWithIndexFallback creates a file server that serves the given filesystem |
| 16 | +// and falls back to index.html for any path that doesn't match a file |
| 17 | +func FileServerWithIndexFallback() http.Handler { |
| 18 | + // First, try to get the embedded files |
| 19 | + subFS, err := fs.Sub(chatStaticFiles, "chat") |
| 20 | + if err != nil { |
| 21 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 22 | + http.Error(w, fmt.Sprintf("failed to get subfs: %s", err), http.StatusInternalServerError) |
| 23 | + }) |
| 24 | + } |
| 25 | + chatFS := http.FS(subFS) |
| 26 | + fileServer := http.FileServer(chatFS) |
| 27 | + |
| 28 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 29 | + path := r.URL.Path |
| 30 | + trimmedPath := strings.TrimPrefix(path, "/") |
| 31 | + fmt.Println("path", trimmedPath) |
| 32 | + if trimmedPath == "" { |
| 33 | + trimmedPath = "index.html" |
| 34 | + } |
| 35 | + |
| 36 | + // Try to serve the file directly |
| 37 | + _, err := chatFS.Open(trimmedPath) |
| 38 | + if err == nil { |
| 39 | + fileServer.ServeHTTP(w, r) |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + // If file doesn't exist, serve 404.html for any path |
| 44 | + if os.IsNotExist(err) { |
| 45 | + r2 := new(http.Request) |
| 46 | + *r2 = *r |
| 47 | + r2.URL.Path = "/404.html" |
| 48 | + fileServer.ServeHTTP(w, r2) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + // For other errors, return the error as is |
| 53 | + http.Error(w, fmt.Sprintf("failed to serve file: %s", err), http.StatusInternalServerError) |
| 54 | + }) |
| 55 | +} |
0 commit comments