增加域名快速处理函数

This commit is contained in:
GoEdgeLab
2021-02-07 09:08:06 +08:00
parent 12e11188db
commit eaca2e64a1
2 changed files with 74 additions and 1 deletions

View File

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

View File

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