From 86b91fef1d3bf1c0c95532c3247ff1e3e51eab4a Mon Sep 17 00:00:00 2001 From: Vladimir Avtsenov Date: Mon, 26 Aug 2024 19:34:45 +0300 Subject: [PATCH] checks for domain --- go.mod | 5 ++++- models/domain.go | 23 +++++++++++++++++++++++ models/domain_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 models/domain_test.go diff --git a/go.mod b/go.mod index 00593c0..897c82d 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,7 @@ module kvas2-go go 1.21 -require github.com/coreos/go-iptables v0.7.0 +require ( + github.com/IGLOU-EU/go-wildcard/v2 v2.0.2 + github.com/coreos/go-iptables v0.7.0 +) diff --git a/models/domain.go b/models/domain.go index 07ac2d0..c1338dc 100644 --- a/models/domain.go +++ b/models/domain.go @@ -1,5 +1,11 @@ package models +import ( + "regexp" + + "github.com/IGLOU-EU/go-wildcard/v2" +) + type Domain struct { ID int Group *Group @@ -8,3 +14,20 @@ type Domain struct { Enable bool Comment string } + +func (d *Domain) IsEnabled() bool { + return d.Enable +} + +func (d *Domain) IsMatch(domainName string) bool { + switch d.Type { + case "wildcard": + return wildcard.Match(d.Domain, domainName) + case "regex": + ok, _ := regexp.MatchString(d.Domain, domainName) + return ok + case "plaintext": + return domainName == d.Domain + } + return false +} diff --git a/models/domain_test.go b/models/domain_test.go new file mode 100644 index 0000000..0b682dc --- /dev/null +++ b/models/domain_test.go @@ -0,0 +1,42 @@ +package models + +import "testing" + +func TestDomain_IsMatch_Plaintext(t *testing.T) { + domain := &Domain{ + Type: "plaintext", + Domain: "example.com", + } + if !domain.IsMatch("example.com") { + t.Fatal("&Domain{Type: \"plaintext\", Domain: \"example.com\"}.IsMatch(\"example.com\") returns false") + } + if domain.IsMatch("noexample.com") { + t.Fatal("&Domain{Type: \"plaintext\", Domain: \"example.com\"}.IsMatch(\"noexample.com\") returns true") + } +} + +func TestDomain_IsMatch_Wildcard(t *testing.T) { + domain := &Domain{ + Type: "wildcard", + Domain: "ex*le.com", + } + if !domain.IsMatch("example.com") { + t.Fatal("&Domain{Type: \"wildcard\", Domain: \"ex*le.com\"}.IsMatch(\"example.com\") returns false") + } + if domain.IsMatch("noexample.com") { + t.Fatal("&Domain{Type: \"wildcard\", Domain: \"ex*le.com\"}.IsMatch(\"noexample.com\") returns true") + } +} + +func TestDomain_IsMatch_RegEx(t *testing.T) { + domain := &Domain{ + Type: "regex", + Domain: "^ex[apm]{3}le.com$", + } + if !domain.IsMatch("example.com") { + t.Fatal("&Domain{Type: \"regex\", Domain: \"^ex[apm]{3}le.com$\"}.IsMatch(\"example.com\") returns false") + } + if domain.IsMatch("noexample.com") { + t.Fatal("&Domain{Type: \"regex\", Domain: \"^ex[apm]{3}le.com$\"}.IsMatch(\"noexample.com\") returns true") + } +}