-
Notifications
You must be signed in to change notification settings - Fork 2
/
validator.go
48 lines (40 loc) · 902 Bytes
/
validator.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
package greetings
import (
"context"
"encoding/json"
"fmt"
"slices"
"github.com/verifa/horizon/pkg/hz"
)
var _ (hz.Validator) = (*GreetingValidator)(nil)
type GreetingValidator struct {
hz.ZeroValidator
}
func (*GreetingValidator) ValidateCreate(
ctx context.Context,
data []byte,
) error {
var greeting Greeting
if err := json.Unmarshal(data, &greeting); err != nil {
return fmt.Errorf("unmarshalling greeting: %w", err)
}
if greeting.Spec == nil {
return fmt.Errorf("spec is required")
}
if greeting.Spec.Name == "" {
return fmt.Errorf("name is required")
}
if !isFriend(greeting.Spec.Name) {
return fmt.Errorf(
"we don't greet strangers in Finland, we only know: %v",
friends,
)
}
return nil
}
var friends = []string{
"Pekka", "Matti", "Jukka", "Kari", "Jari", "Mikko", "Ilkka",
}
func isFriend(name string) bool {
return slices.Contains(friends, name)
}