summaryrefslogtreecommitdiff
path: root/plugin/special/test.go
blob: 6425ca93cc4427a15d4877f32283c6059a842ae8 (plain)
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
package special

import (
	"encoding/json"

	"github.com/Loyalsoldier/geoip/lib"
)

const (
	entryNameTest = "test"
	typeTest      = "test"
	descTest      = "Convert specific CIDR to other formats (for test only)"
)

var testCIDRs = []string{
	"127.0.0.0/8",
}

func init() {
	lib.RegisterInputConfigCreator(typeTest, func(action lib.Action, data json.RawMessage) (lib.InputConverter, error) {
		return NewTestFromBytes(action, data)
	})
	lib.RegisterInputConverter(typeTest, &test{
		Description: descTest,
	})
}

func NewTest(action lib.Action, opts ...lib.InputOption) lib.InputConverter {
	t := &test{
		Type:        typeTest,
		Action:      action,
		Description: descTest,
	}

	for _, opt := range opts {
		if opt != nil {
			opt(t)
		}
	}

	return t
}

func NewTestFromBytes(action lib.Action, data []byte) (lib.InputConverter, error) {
	return NewTest(action), nil
}

type test struct {
	Type        string
	Action      lib.Action
	Description string
}

func (t *test) GetType() string {
	return t.Type
}

func (t *test) GetAction() lib.Action {
	return t.Action
}

func (t *test) GetDescription() string {
	return t.Description
}

func (t *test) Input(container lib.Container) (lib.Container, error) {
	entry := lib.NewEntry(entryNameTest)
	for _, cidr := range testCIDRs {
		if err := entry.AddPrefix(cidr); err != nil {
			return nil, err
		}
	}

	switch t.Action {
	case lib.ActionAdd:
		if err := container.Add(entry); err != nil {
			return nil, err
		}
	case lib.ActionRemove:
		if err := container.Remove(entry, lib.CaseRemovePrefix); err != nil {
			return nil, err
		}
	default:
		return nil, lib.ErrUnknownAction
	}

	return container, nil
}