checks for domain

This commit is contained in:
Vladimir Avtsenov 2024-08-26 19:34:45 +03:00
parent 569c85cc3c
commit 86b91fef1d
3 changed files with 69 additions and 1 deletions

5
go.mod
View File

@ -2,4 +2,7 @@ module kvas2-go
go 1.21 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
)

View File

@ -1,5 +1,11 @@
package models package models
import (
"regexp"
"github.com/IGLOU-EU/go-wildcard/v2"
)
type Domain struct { type Domain struct {
ID int ID int
Group *Group Group *Group
@ -8,3 +14,20 @@ type Domain struct {
Enable bool Enable bool
Comment string 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
}

42
models/domain_test.go Normal file
View File

@ -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")
}
}