-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.go
64 lines (56 loc) · 1.37 KB
/
web.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"embed"
"fmt"
"io"
"io/fs"
"log"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
)
//go:embed _ui/build
var UI embed.FS
var uiFS fs.FS
func init() {
var err error
uiFS, err = fs.Sub(UI, "_ui/build")
if err != nil {
log.Fatal("failed to get ui fs", err)
}
}
func handleStatic(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
path := filepath.Clean(r.URL.Path)
if path == "/" { // Add other paths that you route on the UI side here
path = "index.html"
}
path = strings.TrimPrefix(path, "/")
file, err := uiFS.Open(path)
if err != nil {
if os.IsNotExist(err) {
log.Println("file", path, "not found:", err)
http.NotFound(w, r)
return
}
log.Println("file", path, "cannot be read:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
contentType := mime.TypeByExtension(filepath.Ext(path))
w.Header().Set("Content-Type", contentType)
if strings.HasPrefix(path, "static/") {
w.Header().Set("Cache-Control", "public, max-age=31536000")
}
stat, err := file.Stat()
if err == nil && stat.Size() > 0 {
w.Header().Set("Content-Length", fmt.Sprintf("%d", stat.Size()))
}
n, _ := io.Copy(w, file)
log.Println("file", path, "copied", n, "bytes")
}