-
Notifications
You must be signed in to change notification settings - Fork 1
/
method.go
49 lines (41 loc) · 919 Bytes
/
method.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
package base
import (
"fmt"
"net/http"
"strings"
"github.com/gobuffalo/validate"
"github.com/samber/lo"
)
type MethodValidator struct {
Field string
Value string
AllowEmpty bool
}
var allowedMethods = []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
var lastAllowedMethodIndex = len(allowedMethods) - 1
func (m *MethodValidator) IsValid(errors *validate.Errors) {
if m.AllowEmpty && m.Value == "" {
return
}
if !lo.Contains(allowedMethods, m.Value) {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("%s must be one of ", m.Field))
for i, allowedMethod := range allowedMethods {
builder.WriteString(allowedMethod)
if i != lastAllowedMethodIndex {
builder.WriteString(", ")
}
}
errors.Add(m.Field, builder.String())
}
}