This repository was archived by the owner on Jun 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecurityTxtParser.go
85 lines (72 loc) · 2.31 KB
/
SecurityTxtParser.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
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
package SecurityTxtParser
import (
"regexp"
"strings"
"golang.org/x/exp/slices"
)
type KV struct {
Key string
Value string
}
type SecurityTxt struct {
Contact []string `json:"contact"`
Expires []string `json:"expires"`
Encryption []string `json:"encryption"`
Acknowledgments []string `json:"acknowledgements"`
PreferredLanguages []string `json:"preferred-languages"`
Canonical []string `json:"canonical"`
Policy []string `json:"policy"`
Hiring []string `json:"hiring"`
}
func ParseTxt(txt string) (SecurityTxt, error) {
kvs := getLinesWithKeys(txt)
st := transformToSecurityTxt(kvs)
return st, nil
}
func transformToSecurityTxt(kvs []KV) SecurityTxt {
preferredLanguages := splitEachRemoveDuplicates(
filterForKey(kvs, "Preferred-Languages"), ", ",
)
st := SecurityTxt{
Contact: filterForKey(kvs, "Contact"),
Expires: filterForKey(kvs, "Expires"),
Encryption: filterForKey(kvs, "Encryption"),
Acknowledgments: filterForKey(kvs, "Acknowledgments"),
PreferredLanguages: preferredLanguages,
Canonical: filterForKey(kvs, "Canonical"),
Policy: filterForKey(kvs, "Policy"),
Hiring: filterForKey(kvs, "Hiring"),
}
return st
}
func getLinesWithKeys(text string) []KV {
pattern := regexp.MustCompile("(.*): (.*)")
key_lines := pattern.FindAllStringSubmatch(text, -1)
var key_value []KV
for _, element := range key_lines {
key_value = append(key_value, KV{Key: element[1], Value: element[2]})
}
return key_value
}
// Splits the strings in the string array according to separator, then removes the duplicates
func splitEachRemoveDuplicates(s_arr []string, sep string) []string {
var out []string
for _, item := range s_arr {
parsedItems := strings.Split(item, sep)
for _, currentItem := range parsedItems {
if !slices.Contains(out, currentItem) {
out = append(out, currentItem)
}
}
}
return out
}
func filterForKey(kvs []KV, key string) []string {
var out []string
for _, kv := range kvs {
if kv.Key == key {
out = append(out, kv.Value)
}
}
return out
}