Skip to content

Commit 83965b5

Browse files
committed
fix: serve UI as a SPA
close #75
1 parent 91ddfc2 commit 83965b5

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

pkg/api/index.go

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,44 @@ package api
22

33
import (
44
"net/http"
5+
"os"
56
"path"
7+
"path/filepath"
68

79
"github.com/ncarlier/readflow/pkg/config"
810
"github.com/rs/zerolog/log"
911
)
1012

13+
type SPAHandler struct {
14+
baseDir string
15+
handler http.Handler
16+
}
17+
18+
func newSPAHandler(baseDir string) http.Handler {
19+
return &SPAHandler{
20+
baseDir: baseDir,
21+
handler: http.FileServer(http.Dir(baseDir)),
22+
}
23+
}
24+
25+
func (s SPAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
26+
path := filepath.Join(s.baseDir, r.URL.Path)
27+
fi, err := os.Stat(path)
28+
if os.IsNotExist(err) || fi.IsDir() {
29+
// serve index.html if path does not exist
30+
http.ServeFile(w, r, filepath.Join(s.baseDir, "index.html"))
31+
return
32+
}
33+
34+
if err != nil {
35+
http.Error(w, err.Error(), http.StatusInternalServerError)
36+
return
37+
}
38+
39+
// otherwise,serve static files
40+
s.handler.ServeHTTP(w, r)
41+
}
42+
1143
// index is the handler to show API details.
1244
func index(conf *config.Config) http.Handler {
1345
if conf.UI.Directory != "" {
@@ -17,7 +49,7 @@ func index(conf *config.Config) http.Handler {
1749
if err := conf.WriteUIConfigFile(configFilename); err != nil {
1850
log.Warn().Err(err).Str("filename", configFilename).Msg("unable to generate UI config file")
1951
}
20-
return http.FileServer(http.Dir(conf.UI.Directory))
52+
return newSPAHandler(conf.UI.Directory)
2153
}
2254
return http.RedirectHandler("/info", http.StatusSeeOther)
2355
}

0 commit comments

Comments
 (0)