Skip to content

Commit

Permalink
fix: serve UI as a SPA
Browse files Browse the repository at this point in the history
close #75
  • Loading branch information
ncarlier committed Mar 17, 2024
1 parent 91ddfc2 commit 83965b5
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion pkg/api/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,44 @@ package api

import (
"net/http"
"os"
"path"
"path/filepath"

"github.com/ncarlier/readflow/pkg/config"
"github.com/rs/zerolog/log"
)

type SPAHandler struct {
baseDir string
handler http.Handler
}

func newSPAHandler(baseDir string) http.Handler {
return &SPAHandler{
baseDir: baseDir,
handler: http.FileServer(http.Dir(baseDir)),
}
}

func (s SPAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := filepath.Join(s.baseDir, r.URL.Path)
fi, err := os.Stat(path)
if os.IsNotExist(err) || fi.IsDir() {
// serve index.html if path does not exist
http.ServeFile(w, r, filepath.Join(s.baseDir, "index.html"))
return
}

if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

// otherwise,serve static files
s.handler.ServeHTTP(w, r)
}

// index is the handler to show API details.
func index(conf *config.Config) http.Handler {
if conf.UI.Directory != "" {
Expand All @@ -17,7 +49,7 @@ func index(conf *config.Config) http.Handler {
if err := conf.WriteUIConfigFile(configFilename); err != nil {
log.Warn().Err(err).Str("filename", configFilename).Msg("unable to generate UI config file")
}
return http.FileServer(http.Dir(conf.UI.Directory))
return newSPAHandler(conf.UI.Directory)
}
return http.RedirectHandler("/info", http.StatusSeeOther)
}

0 comments on commit 83965b5

Please sign in to comment.