diff --git a/pkg/serverconfigs/server_name_config.go b/pkg/serverconfigs/server_name_config.go index a551ecf..e7b9398 100644 --- a/pkg/serverconfigs/server_name_config.go +++ b/pkg/serverconfigs/server_name_config.go @@ -1,6 +1,10 @@ package serverconfigs -import "github.com/TeaOSLab/EdgeCommon/pkg/configutils" +import ( + "github.com/TeaOSLab/EdgeCommon/pkg/configutils" + "github.com/iwind/TeaGo/lists" + "strings" +) type ServerNameType = string @@ -18,6 +22,14 @@ type ServerNameConfig struct { SubNames []string `yaml:"subNames" json:"subNames"` // 子名称,用来支持大量的域名批量管理 } +// 格式化域名 +func (this *ServerNameConfig) Normalize() { + this.Name = strings.ToLower(this.Name) + for index, subName := range this.SubNames { + this.SubNames[index] = strings.ToLower(subName) + } +} + // 判断主机名是否匹配 func (this *ServerNameConfig) Match(name string) bool { if len(this.SubNames) > 0 { @@ -25,3 +37,29 @@ func (this *ServerNameConfig) Match(name string) bool { } return configutils.MatchDomains([]string{this.Name}, name) } + +// 格式化一组域名 +func NormalizeServerNames(serverNames []*ServerNameConfig) { + for _, serverName := range serverNames { + serverName.Normalize() + } +} + +// 获取所有域名 +func PlainServerNames(serverNames []*ServerNameConfig) (result []string) { + NormalizeServerNames(serverNames) + for _, serverName := range serverNames { + if len(serverName.SubNames) == 0 { + if len(serverName.Name) > 0 && !lists.ContainsString(result, serverName.Name) { + result = append(result, serverName.Name) + } + } else { + for _, subName := range serverName.SubNames { + if len(subName) > 0 && !lists.ContainsString(result, subName) { + result = append(result, subName) + } + } + } + } + return result +} diff --git a/pkg/serverconfigs/server_name_config_test.go b/pkg/serverconfigs/server_name_config_test.go new file mode 100644 index 0000000..f80cb61 --- /dev/null +++ b/pkg/serverconfigs/server_name_config_test.go @@ -0,0 +1,35 @@ +package serverconfigs + +import ( + "github.com/iwind/TeaGo/logs" + "testing" +) + +func TestNormalizeServerNames(t *testing.T) { + serverNames := []*ServerNameConfig{ + { + Name: "Hello.com", + SubNames: []string{"WoRld.com", "XYZ.com"}, + }, + } + NormalizeServerNames(serverNames) + logs.PrintAsJSON(serverNames, t) +} + +func TestPlainServerNames(t *testing.T) { + serverNames := []*ServerNameConfig{ + { + Name: "Hello.com", + SubNames: nil, + }, + { + Name: "world.com", + SubNames: nil, + }, + { + Name: "", + SubNames: []string{"WoRld.com", "XYZ.com"}, + }, + } + logs.PrintAsJSON(PlainServerNames(serverNames), t) +}