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
|
package static
import (
rrttp "github.com/spiral/roadrunner/service/http"
"net/http"
"path"
)
// ID contains default service name.
const ID = "static"
// Service serves static files. Potentially convert into middleware?
type Service struct {
// server configuration (location, forbidden files and etc)
cfg *Config
// root is initiated http directory
root http.Dir
}
// Init must return configure service and return true if service hasStatus enabled. Must return error in case of
// misconfiguration. Services must not be used without proper configuration pushed first.
func (s *Service) Init(cfg *Config, r *rrttp.Service) (bool, error) {
if r == nil {
return false, nil
}
s.cfg = cfg
s.root = http.Dir(s.cfg.Dir)
r.AddMiddleware(s.middleware)
return true, nil
}
// middleware must return true if request/response pair is handled within the middleware.
func (s *Service) middleware(f http.HandlerFunc) http.HandlerFunc {
// Define the http.HandlerFunc
return func(w http.ResponseWriter, r *http.Request) {
if !s.handleStatic(w, r) {
f(w, r)
}
}
}
func (s *Service) handleStatic(w http.ResponseWriter, r *http.Request) bool {
fPath := path.Clean(r.URL.Path)
if s.cfg.Forbids(fPath) {
return false
}
f, err := s.root.Open(fPath)
if err != nil {
return false
}
defer f.Close()
d, err := f.Stat()
if err != nil {
return false
}
// do not serve directories
if d.IsDir() {
return false
}
http.ServeContent(w, r, d.Name(), d.ModTime(), f)
return true
}
|