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
|
package static
import (
"github.com/spiral/roadrunner/service"
rrttp "github.com/spiral/roadrunner/service/http"
"net/http"
"path"
"strings"
)
// 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 service.Config, c service.Container) (enabled bool, err error) {
config := &Config{}
if err := cfg.Unmarshal(config); err != nil {
return false, err
}
if !config.Enable {
return false, nil
}
if err := config.Valid(); err != nil {
return false, err
}
s.cfg = config
s.root = http.Dir(s.cfg.Dir)
// registering as middleware
if h, ok := c.Get(rrttp.ID); ok >= service.StatusConfigured {
if h, ok := h.(*rrttp.Service); ok {
h.AddMiddleware(s.middleware)
}
}
return true, nil
}
// Serve serves the service.
func (s *Service) Serve() error { return nil }
// Stop stops the service.
func (s *Service) Stop() {}
// middleware must return true if request/response pair is handled within the middleware.
func (s *Service) middleware(w http.ResponseWriter, r *http.Request) bool {
fPath := r.URL.Path
if !strings.HasPrefix(fPath, "/") {
fPath = "/" + fPath
}
fPath = path.Clean(fPath)
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
}
|