Skip to content

Commit 43c1127

Browse files
committed
Add support for SPA serve
1 parent 2374a3b commit 43c1127

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

simplehttp2server.go

+29-4
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"flag"
2424
"fmt"
2525
"io"
26+
"io/ioutil"
2627
"log"
2728
"math/big"
2829
mrand "math/rand"
@@ -52,6 +53,7 @@ var (
5253
pushManifest = flag.String("pushmanifest", "push.json", "File containing the push manifest")
5354
minDelay = flag.Int("mindelay", 0, "Minimum delay before a request in answered in milliseconds (ignored without -maxdelay)")
5455
maxDelay = flag.Int("maxdelay", 0, "Maximum delay before a request in answered in milliseconds")
56+
spa = flag.String("spa", "", "Page to serve instead of 404")
5557
)
5658

5759
func init() {
@@ -96,11 +98,25 @@ func main() {
9698
}
9799
time.Sleep(time.Duration(delay) * time.Millisecond)
98100

99-
defer fs.ServeHTTP(w, r)
100-
if *http1 {
101-
return
101+
if *spa != "" {
102+
path := r.URL.Path
103+
if _, err := os.Stat("." + path); err == nil {
104+
fs.ServeHTTP(w, r)
105+
} else {
106+
spaContents, err := readSPAFile(*spa)
107+
if err != nil {
108+
http.Error(w, fmt.Sprintf("Could not read SPA file: %s", err), http.StatusInternalServerError)
109+
return
110+
}
111+
w.Write(spaContents)
112+
}
113+
} else {
114+
fs.ServeHTTP(w, r)
115+
}
116+
117+
if !*http1 {
118+
pushResources(w, r)
102119
}
103-
pushResources(w, r)
104120
})
105121

106122
if err := configureTLS(server); err != nil {
@@ -150,6 +166,15 @@ func pushResources(w http.ResponseWriter, r *http.Request) {
150166
}
151167
}
152168

169+
func readSPAFile(path string) ([]byte, error) {
170+
f, err := os.Open(path)
171+
if err != nil {
172+
return nil, err
173+
}
174+
defer f.Close()
175+
return ioutil.ReadAll(f)
176+
}
177+
153178
type GzipResponseWriter struct {
154179
io.WriteCloser
155180
http.ResponseWriter

0 commit comments

Comments
 (0)