forked from garethgeorge/backrest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webui.go
50 lines (42 loc) · 1 KB
/
webui.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package webui
import (
"bytes"
"io"
"io/fs"
"net/http"
"strings"
)
func Handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") {
r.URL.Path += "index.html"
}
f, err := content.Open(contentPrefix + r.URL.Path + ".gz")
if err == nil {
defer f.Close()
w.Header().Set("Content-Encoding", "gzip")
serveFile(f, w, r, r.URL.Path)
return
}
f, err = content.Open(contentPrefix + r.URL.Path)
if err == nil {
defer f.Close()
serveFile(f, w, r, r.URL.Path)
return
}
http.Error(w, "Not found", http.StatusNotFound)
})
}
func serveFile(f fs.File, w http.ResponseWriter, r *http.Request, path string) {
data, err := io.ReadAll(f)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stat, err := f.Stat()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.ServeContent(w, r, path, stat.ModTime(), bytes.NewReader(data))
}