@@ -2,12 +2,44 @@ package api
2
2
3
3
import (
4
4
"net/http"
5
+ "os"
5
6
"path"
7
+ "path/filepath"
6
8
7
9
"github.com/ncarlier/readflow/pkg/config"
8
10
"github.com/rs/zerolog/log"
9
11
)
10
12
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
+
11
43
// index is the handler to show API details.
12
44
func index (conf * config.Config ) http.Handler {
13
45
if conf .UI .Directory != "" {
@@ -17,7 +49,7 @@ func index(conf *config.Config) http.Handler {
17
49
if err := conf .WriteUIConfigFile (configFilename ); err != nil {
18
50
log .Warn ().Err (err ).Str ("filename" , configFilename ).Msg ("unable to generate UI config file" )
19
51
}
20
- return http . FileServer ( http . Dir ( conf .UI .Directory ) )
52
+ return newSPAHandler ( conf .UI .Directory )
21
53
}
22
54
return http .RedirectHandler ("/info" , http .StatusSeeOther )
23
55
}
0 commit comments