summaryrefslogtreecommitdiff
path: root/static/service.go
blob: eab9fe498903362d5521542dbb6ecc84b2c43474 (plain)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package static

import (
	"github.com/sirupsen/logrus"
	"net/http"
	"os"
	"path"
	"strings"
	rrttp "github.com/spiral/roadrunner/http"
	"github.com/spiral/roadrunner/service"
)

// Name contains default service name.
const Name = "static-server"

// Service serves static files. Potentially convert into middleware?
type Service struct {
	// Logger is associated debug and error logger. Can be empty.
	Logger *logrus.Logger

	// server configuration (location, forbidden files and etc)
	cfg *Config

	// root is initiated http directory
	root http.Dir

	// let's service stay running
	done chan interface{}
}

// 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.Add(s)
		}
	} else {
		if s.Logger != nil {
			s.Logger.Warningf("no http service found")
		}
	}

	return true, nil
}

// Serve serves the service.
func (s *Service) Serve() error {
	s.done = make(chan interface{})
	<-s.done

	return nil
}

// Stop stops the service.
func (s *Service) Stop() {
	//todo: this is not safe (TODO CHECK IT?)
	close(s.done)
}

// 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) {
		if s.Logger != nil {
			s.Logger.Warningf("attempt to access forbidden file %s", fPath)
		}
		return false
	}

	f, err := s.root.Open(fPath)
	if err != nil {
		if !os.IsNotExist(err) {
			if s.Logger != nil {
				s.Logger.Error(err)
			}
		}

		return false
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		if s.Logger != nil {
			s.Logger.Error(err)
		}
		return false
	}

	// do not Handle directories
	if d.IsDir() {
		return false
	}

	http.ServeContent(w, r, d.Name(), d.ModTime(), f)
	return true
}