-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredirectrules.go
More file actions
72 lines (59 loc) · 1.67 KB
/
Copy pathredirectrules.go
File metadata and controls
72 lines (59 loc) · 1.67 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
67
68
69
70
71
72
package zeaburcaddyextension
import (
"bufio"
"log/slog"
"strconv"
"strings"
)
// RedirectRule represents a single redirect rule.
type RedirectRule struct {
SourcePath string
TargetPath string
StatusCode int
Conditions string
}
// ParseRedirects takes a string containing the contents of a _redirects file
// and returns a slice of RedirectRule structs, ignoring any invalid lines.
func ParseRedirects(content string) ([]RedirectRule, error) {
var rules []RedirectRule
scanner := bufio.NewScanner(strings.NewReader(content))
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") { // Skip empty lines and comments
continue
}
parts := strings.Fields(line)
if len(parts) < 3 {
slog.Warn("Skipping invalid redirect rule", "line", line)
continue
}
statusCode, err := strconv.Atoi(parts[2])
if err != nil {
slog.Warn("Skipping invalid status code in redirect rule", "line", line)
continue
}
if !strings.HasPrefix(parts[0], "/") {
slog.Warn("Skipping invalid source path in redirect rule", "line", line)
continue
}
if !strings.HasPrefix(parts[1], "/") && !strings.HasPrefix(parts[1], "http://") && !strings.HasPrefix(parts[1], "https://") {
slog.Warn("Skipping invalid target path in redirect rule", "line", line)
continue
}
rule := RedirectRule{
SourcePath: parts[0],
TargetPath: parts[1],
StatusCode: statusCode,
}
// Store conditions as a single string if present
if len(parts) > 3 {
rule.Conditions = strings.Join(parts[3:], " ")
}
rules = append(rules, rule)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return rules, nil
}