-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.go
73 lines (61 loc) · 1.89 KB
/
validate.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
package main
import (
"fmt"
"reflect"
"strings"
)
// ValidationError Errors from validation of models.
type ValidationError struct {
Type string `json:"type"`
Errors map[string]string `json:"errors"`
}
func (f ValidationError) Error() string {
return fmt.Sprintf("Invalid values found during validation of %s", f.Type)
}
// NewValidationError Create a validation error object for an object.
func NewValidationError(m interface{}) ValidationError {
return ValidationError{
Type: reflect.TypeOf(m).Name(),
Errors: make(map[string]string),
}
}
// Validate Account type.
func (msg *Linkk) Validate() error {
validationErrors := NewValidationError(*msg)
// Paths start with a /.
if !strings.HasPrefix(msg.Path, "/") {
validationErrors.Errors["Path"] = "Path must start with a /."
}
// Paths cannot end with a /.
if strings.HasSuffix(msg.Path, "/") {
validationErrors.Errors["Path"] = "Path cannot end with a /."
}
// Paths cannot be root.
if msg.Path == "/" {
validationErrors.Errors["Path"] = "Path cannot be root."
}
// Paths cannot start with a reserved prefix.
reservedPrefixes := []string{
"/_/", "/_ah/", "/~/",
"/css/", "/js/", "/static/",
"/favicon.ico", "/robots.txt", "/sitemap.xml",
}
prefix := stringPrefixInSlice(msg.Path, reservedPrefixes)
if prefix != "" ||
stringInSlice(msg.Path, reservedPrefixes) ||
stringInSlice(msg.Path+"/", reservedPrefixes) {
if prefix == "" {
prefix = msg.Path
}
validationErrors.Errors["Path"] = fmt.Sprintf("Path cannot start with a reserved prefix: %s.", prefix)
}
// URL needs to start with the right protocols.
validProtocols := []string{"http://", "https://"}
if stringPrefixInSlice(msg.URL, validProtocols) == "" {
validationErrors.Errors["URL"] = fmt.Sprintf("Url needs to have a valid protocol: %v.", validProtocols)
}
if len(validationErrors.Errors) > 0 {
return validationErrors
}
return nil
}