forked from traefik/plugin-blockpath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockpath.go
58 lines (47 loc) · 1.18 KB
/
blockpath.go
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
// Package traefik_plugin_blockpath a plugin to block a path.
package traefik_plugin_blockpath
import (
"context"
"fmt"
"net/http"
"regexp"
)
// Config holds the plugin configuration.
type Config struct {
Regex []string `json:"regex,omitempty"`
}
// CreateConfig creates and initializes the plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
type blockPath struct {
name string
next http.Handler
regexps []*regexp.Regexp
}
// New creates and returns a plugin instance.
func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
regexps := make([]*regexp.Regexp, len(config.Regex))
for i, regex := range config.Regex {
re, err := regexp.Compile(regex)
if err != nil {
return nil, fmt.Errorf("error compiling regex %q: %w", regex, err)
}
regexps[i] = re
}
return &blockPath{
name: name,
next: next,
regexps: regexps,
}, nil
}
func (b *blockPath) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
currentPath := req.URL.EscapedPath()
for _, re := range b.regexps {
if re.MatchString(currentPath) {
rw.WriteHeader(http.StatusForbidden)
return
}
}
b.next.ServeHTTP(rw, req)
}