This repository has been archived by the owner on Jan 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
check-mandatory.go
98 lines (81 loc) · 1.84 KB
/
check-mandatory.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
86
87
88
89
90
91
92
93
94
95
96
97
98
//
// Check that mandatory fields are present.
//
package main
import (
"fmt"
"reflect"
"regexp"
"strings"
)
//
// Register ourself as a blogspam-plugin.
//
func init() {
registerPlugin(BlogspamPlugin{Name: "30-mandatory.js",
Description: "Look for any mandatory fields which might be missing.",
Author: "Steve Kemp <[email protected]>",
Test: validateMandatory})
}
//
// Test that mandatory fields are present.
//
func validateMandatory(x Submission) (PluginResult, string) {
//
// The mandatory fields we're going to insist upon by default
//
tmp := make(map[string]int)
tmp["site"] = 1
tmp["comment"] = 1
tmp["ip"] = 1
//
// Do we have options?
//
if len(x.Options) > 0 {
//
// Split them into an array, based on commas
//
options := strings.Split(x.Options, ",")
//
// Now look for any additional mandatory fields
//
for _, option := range options {
re := regexp.MustCompile("mandatory=([^=]+)$")
match := re.FindStringSubmatch(option)
if len(match) > 0 {
tmp[match[1]] = 1
}
}
}
//
// Now we can do the test for missing fields.
//
// There __must__ be a better way of doing this, by looking
// at the subject field with reflection.
//
for field := range tmp {
//
// Get all the fields of the structure, via reflection
//
s := reflect.ValueOf(&x).Elem()
typeOfT := s.Type()
//
// Iterate over the fields.
//
for i := 0; i < s.NumField(); i++ {
// The specific field
f := s.Field(i)
// The name/value of the field
fieldName := typeOfT.Field(i).Name
fieldVal := fmt.Sprintf("%s", f.Interface())
// Is this the field we're looking for?
if strings.EqualFold(field, fieldName) {
// Then raise an error if it is empty
if len(fieldVal) < 1 {
return Spam, fmt.Sprintf("Field %s is missing", fieldName)
}
}
}
}
return Undecided, ""
}