diff options
author | Wolfy-J <[email protected]> | 2018-06-11 11:28:24 +0300 |
---|---|---|
committer | Wolfy-J <[email protected]> | 2018-06-11 11:28:24 +0300 |
commit | 2f135b359575cc1625d1461bb6d8e478da8ccf54 (patch) | |
tree | 8561f84318c3a291f4a38df6b347954bda777e41 /service/static/service.go | |
parent | 6efaa0aa951240c2bb643761f103ee3f0fafb4d9 (diff) |
refactor
Diffstat (limited to 'service/static/service.go')
-rw-r--r-- | service/static/service.go | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/service/static/service.go b/service/static/service.go new file mode 100644 index 00000000..5c3defe6 --- /dev/null +++ b/service/static/service.go @@ -0,0 +1,88 @@ +package static + +import ( + "net/http" + "path" + "strings" + rrttp "github.com/spiral/roadrunner/service/http" + "github.com/spiral/roadrunner/service" +) + +// Name contains default service name. +const Name = "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 +} + +// Configure 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) Configure(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.Name); ok >= service.StatusConfigured { + if h, ok := h.(*rrttp.Service); ok { + h.AddMiddleware(s) + } + } + + return true, nil +} + +// Serve serves the service. +func (s *Service) Serve() error { return nil } + +// Stop stops the service. +func (s *Service) Stop() {} + +// Handle must return true if request/response pair is handled withing the middleware. +func (s *Service) Handle(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 Handle directories + if d.IsDir() { + return false + } + + http.ServeContent(w, r, d.Name(), d.ModTime(), f) + return true +} |