summaryrefslogtreecommitdiff
path: root/plugins/static/plugin.go
blob: cf5cee259f420f1e27d3672f7c555e28d5e08e83 (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
package static

import (
	"net/http"
	"path"

	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/interfaces/log"
	"github.com/spiral/roadrunner/v2/plugins/config"
)

// ID contains default service name.
const PluginName = "static"

const RootPluginName = "http"

// Plugin serves static files. Potentially convert into middleware?
type Plugin struct {
	// server configuration (location, forbidden files and etc)
	cfg *Config

	log log.Logger

	// 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 *Plugin) Init(cfg config.Configurer, log log.Logger) error {
	const op = errors.Op("static plugin init")
	err := cfg.UnmarshalKey(RootPluginName, &s.cfg)
	if err != nil {
		return errors.E(op, errors.Disabled, err)
	}

	s.log = log
	s.root = http.Dir(s.cfg.Static.Dir)

	err = s.cfg.Valid()
	if err != nil {
		return errors.E(op, errors.Disabled, err)
	}

	return nil
}

func (s *Plugin) Name() string {
	return PluginName
}

// middleware must return true if request/response pair is handled within the middleware.
func (s *Plugin) Middleware(next http.Handler) http.HandlerFunc {
	// Define the http.HandlerFunc
	return func(w http.ResponseWriter, r *http.Request) {
		if s.cfg.Static.Request != nil {
			for k, v := range s.cfg.Static.Request {
				r.Header.Add(k, v)
			}
		}

		if s.cfg.Static.Response != nil {
			for k, v := range s.cfg.Static.Response {
				w.Header().Set(k, v)
			}
		}

		if !s.handleStatic(w, r) {
			next.ServeHTTP(w, r)
		}
	}
}

func (s *Plugin) handleStatic(w http.ResponseWriter, r *http.Request) bool {
	fPath := path.Clean(r.URL.Path)

	if s.cfg.AlwaysForbid(fPath) {
		return false
	}

	f, err := s.root.Open(fPath)
	if err != nil {
		s.log.Error("file open error", "error", err)
		if s.cfg.AlwaysServe(fPath) {
			w.WriteHeader(404)
			return true
		}

		return false
	}
	defer func() {
		err = f.Close()
		if err != nil {
			s.log.Error("file closing error", "error", err)
		}
	}()

	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
}