Files
EdgeCommon/pkg/serverconfigs/network_address_config.go

92 lines
2.3 KiB
Go
Raw Normal View History

2020-09-13 19:27:47 +08:00
package serverconfigs
import (
2020-09-27 15:25:52 +08:00
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"github.com/iwind/TeaGo/rands"
2020-09-13 19:27:47 +08:00
"github.com/iwind/TeaGo/types"
"regexp"
"strconv"
"strings"
)
var regexpSinglePort = regexp.MustCompile(`^\d+$`)
// 网络地址配置
type NetworkAddressConfig struct {
2020-09-15 14:44:38 +08:00
Protocol Protocol `yaml:"protocol" json:"protocol"` // 协议http、tcp、tcp4、tcp6、unix、udp等
2020-09-27 15:25:52 +08:00
Host string `yaml:"host" json:"host"` // 主机地址或主机名,支持变量
2020-09-15 14:44:38 +08:00
PortRange string `yaml:"portRange" json:"portRange"` // 端口范围,支持 8080、8080-8090、8080:8090
2020-09-13 19:27:47 +08:00
minPort int
maxPort int
2020-09-27 15:25:52 +08:00
hostHasVariables bool
2020-09-13 19:27:47 +08:00
}
2020-09-27 15:25:52 +08:00
// 初始化
2020-09-13 19:27:47 +08:00
func (this *NetworkAddressConfig) Init() error {
2020-09-27 15:25:52 +08:00
this.hostHasVariables = configutils.HasVariables(this.Host)
2020-09-13 19:27:47 +08:00
// 8080
if regexpSinglePort.MatchString(this.PortRange) {
this.minPort = types.Int(this.PortRange)
this.maxPort = this.minPort
return nil
}
// 8080:8090
if strings.Contains(this.PortRange, ":") {
pieces := strings.SplitN(this.PortRange, ":", 2)
minPort := types.Int(pieces[0])
maxPort := types.Int(pieces[1])
if minPort > maxPort {
minPort, maxPort = maxPort, minPort
}
this.minPort = minPort
this.maxPort = maxPort
return nil
}
// 8080-8090
if strings.Contains(this.PortRange, "-") {
pieces := strings.SplitN(this.PortRange, "-", 2)
minPort := types.Int(pieces[0])
maxPort := types.Int(pieces[1])
if minPort > maxPort {
minPort, maxPort = maxPort, minPort
}
this.minPort = minPort
this.maxPort = maxPort
return nil
}
return nil
}
2020-09-27 15:25:52 +08:00
// 所有的地址列表包含scheme
2020-09-13 19:27:47 +08:00
func (this *NetworkAddressConfig) FullAddresses() []string {
if this.Protocol == ProtocolUnix {
2020-09-15 14:44:38 +08:00
return []string{this.Protocol.String() + ":" + this.Host}
2020-09-13 19:27:47 +08:00
}
result := []string{}
for i := this.minPort; i <= this.maxPort; i++ {
host := this.Host
2020-09-15 14:44:38 +08:00
result = append(result, this.Protocol.String()+"://"+host+":"+strconv.Itoa(i))
2020-09-13 19:27:47 +08:00
}
return result
}
2020-09-27 15:25:52 +08:00
// 选择其中一个地址
func (this *NetworkAddressConfig) PickAddress() string {
if this.maxPort > this.minPort {
return this.Host + ":" + strconv.Itoa(rands.Int(this.minPort, this.maxPort))
}
return this.Host + ":" + strconv.Itoa(this.minPort)
}
// 判断Host是否包含变量
func (this *NetworkAddressConfig) HostHasVariables() bool {
return this.hostHasVariables
}