-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic.go
92 lines (83 loc) · 2.55 KB
/
static.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright (c) 2023 William Dode. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
package webo
import (
"io/fs"
"net/http"
"strconv"
"strings"
)
// gorilla mux
// r.PathPrefix("/static").HandlerFunc(nil)
type static struct {
path string
maxAge int
origin string
fileServer http.Handler // http.FileServer
}
func (s static) handler() func(next http.Handler) http.Handler {
path := s.path
if path == "" {
path = "/static"
}
if len(path) > 0 && path[0] != '/' {
path = "/" + s.path
}
hdl := http.StripPrefix(path, s.fileServer)
max_age := strconv.Itoa(s.maxAge)
// must inform router that this path exists
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.RequestURI, path+"/") {
// log.Println(r.Method, r.RequestURI)
w.Header().Set("Cache-Control", "max-age="+max_age)
if s.origin != "" {
w.Header().Set("Access-Control-Allow-Origin", s.origin)
}
hdl.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r)
})
}
}
// with gorilla mux.Router (gorilla must know that /static exists)
// add a static middleware from disk
// with :
// Cache-Control max-age=maxAge
func StaticDiskMiddleware(path string, maxAge int) func(next http.Handler) http.Handler {
return StaticDiskMiddlewareOrigin(path, maxAge, "")
}
// with gorilla mux.Router (gorilla must know that /static exists)
// add a static middleware from disk
// with :
// Cache-Control max-age=maxAge
// Access-Control-Allow-Origin origin
func StaticDiskMiddlewareOrigin(path string, maxAge int, origin string) func(next http.Handler) http.Handler {
return static{
path: path,
maxAge: maxAge,
origin: origin,
fileServer: http.FileServer(JustFiles{http.Dir(path)}),
}.handler()
}
// with gorilla mux.Router (gorilla must know that /static exists)
// add a static middleware from fs.FS
// with :
// Cache-Control maxAge
func StaticFsMiddleware(path string, fs fs.FS, maxAge int) func(next http.Handler) http.Handler {
return StaticFsMiddlewareOrigin(path, fs, maxAge, "")
}
// with gorilla mux.Router (gorilla must know that /static exists)
// add a static middleware from fs.FS
// with :
// Cache-Control max-age=maxAge
// Access-Control-Allow-Origin origin
func StaticFsMiddlewareOrigin(path string, fs fs.FS, maxAge int, origin string) func(next http.Handler) http.Handler {
return static{
path: path,
maxAge: maxAge,
origin: origin,
fileServer: http.FileServer(http.FS(fs)),
}.handler()
}