-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
63 lines (51 loc) · 1.08 KB
/
service.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
package static
import (
"context"
"embed"
"github.com/gorilla/mux"
"io/fs"
"net/http"
"os"
"path/filepath"
)
const assetPath = "assets"
const indexPath = "assets/index.html"
//go:embed assets
var assetsFS embed.FS
type FS struct {
fs.FS
}
func (f FS) Open(name string) (fs.File, error) {
name = filepath.Join(assetPath, name)
r, err := f.FS.Open(name)
if os.IsNotExist(err) {
return f.FS.Open(indexPath)
}
return r, err
}
type Service struct{}
func (s Service) RegisterRoutes(router *mux.Router) {
router.PathPrefix("/").Handler(s)
}
func (s Service) Run(context.Context) {
}
func (s Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
setCacheHeader(w, r)
http.FileServer(http.FS(FS{assetsFS})).ServeHTTP(w, r)
}
func setCacheHeader(w http.ResponseWriter, r *http.Request) {
extension := filepath.Ext(r.URL.Path)
switch extension {
case ".woff2":
fallthrough
case ".css":
fallthrough
case ".ico":
fallthrough
case ".js":
w.Header().Set("Cache-Control", "max-age=31536000") // 1y
break
default:
w.Header().Set("Cache-Control", "no-cache")
}
}