-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathblockpath.go
More file actions
66 lines (54 loc) · 1.36 KB
/
blockpath.go
File metadata and controls
66 lines (54 loc) · 1.36 KB
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
// Package plugin_blockpath a plugin to block a path.
package plugin_blockpath
import (
"context"
"fmt"
"net/http"
"regexp"
)
// Config holds the plugin configuration.
type Config struct {
Regex []string `json:"regex,omitempty"`
Code *int `json:"code,omitempty"` // Optional: Status code to respond with, defaults to 403 Forbidden
}
// CreateConfig creates and initializes the plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
type blockPath struct {
name string
next http.Handler
regexps []*regexp.Regexp
code int
}
// 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
}
code := http.StatusForbidden
if config.Code != nil {
code = *config.Code
}
return &blockPath{
name: name,
next: next,
regexps: regexps,
code: code,
}, 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(b.code)
return
}
}
b.next.ServeHTTP(rw, req)
}