优化代码

This commit is contained in:
GoEdgeLab
2023-08-08 15:12:28 +08:00
parent a7a170f9c6
commit 98eac40783
21 changed files with 61 additions and 78 deletions

View File

@@ -7,7 +7,7 @@ import (
var whitespaceReg = regexp.MustCompile(`\s+`)
// 关键词匹配
// MatchKeyword 关键词匹配
func MatchKeyword(source, keyword string) bool {
if len(keyword) == 0 {
return false
@@ -16,7 +16,7 @@ func MatchKeyword(source, keyword string) bool {
pieces := whitespaceReg.Split(keyword, -1)
source = strings.ToLower(source)
for _, piece := range pieces {
if strings.Index(source, strings.ToLower(piece)) > -1 {
if strings.Contains(source, strings.ToLower(piece)) {
return true
}
}

View File

@@ -46,7 +46,7 @@ func NewReader(reader io.Reader) (*Reader, error) {
// 从Reader中加载数据
func (this *Reader) load(reader io.Reader) error {
var buf = make([]byte, 1024)
var metaLine = []byte{}
var metaLine []byte
var metaLineFound = false
var dataBuf = []byte{}
for {

View File

@@ -13,7 +13,7 @@ import (
type FileReader struct {
rawReader *Reader
password string
//password string
}
func NewFileReader(path string, password string) (*FileReader, error) {

View File

@@ -9,15 +9,15 @@ import (
type UnicodeEncodeFilter struct {
}
// 初始化
// Init 初始化
func (this *UnicodeEncodeFilter) Init() error {
return nil
}
// 执行过滤
// Do 执行过滤
func (this *UnicodeEncodeFilter) Do(input interface{}, options interface{}) (output interface{}, goNext bool, err error) {
s := []rune(types.String(input))
result := strings.Builder{}
var s = types.String(input)
var result = strings.Builder{}
for _, r := range s {
if r < 128 {
result.WriteRune(r)

View File

@@ -304,7 +304,7 @@ var AllCheckpoints = []*HTTPFirewallCheckpointDefinition{
RightLabel: "秒",
MaxLength: 8,
Validate: func(value string) (ok bool, message string) {
if regexp.MustCompile("^\\d+$").MatchString(value) {
if regexp.MustCompile(`^\d+$`).MatchString(value) {
ok = true
return
}

View File

@@ -71,29 +71,3 @@ func (this *HTTPAuthBaseMethod) MatchRequest(req *http.Request) bool {
return true
}
// cleanPath 清理Path中的多余的字符
func (this *HTTPAuthBaseMethod) cleanPath(path string) string {
var l = len(path)
if l == 0 {
return "/"
}
var result = []byte{'/'}
var isSlash = true
for i := 0; i < l; i++ {
if path[i] == '?' {
result = append(result, path[i:]...)
break
}
if path[i] == '\\' || path[i] == '/' {
if !isSlash {
isSlash = true
result = append(result, '/')
}
} else {
isSlash = false
result = append(result, path[i])
}
}
return string(result)
}

View File

@@ -2,8 +2,10 @@ package serverconfigs
import (
"errors"
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/iwind/TeaGo/maps"
"net"
"path/filepath"
"regexp"
"time"
@@ -60,11 +62,11 @@ func (this *HTTPFastcgiConfig) Init() error {
}
// 校验地址
if regexp.MustCompile("^\\d+$").MatchString(this.Address) {
if regexp.MustCompile(`^\d+$`).MatchString(this.Address) {
this.network = "tcp"
this.address = "127.0.0.1:" + this.Address
} else if regexp.MustCompile("^(.*):(\\d+)$").MatchString(this.Address) {
matches := regexp.MustCompile("^(.*):(\\d+)$").FindStringSubmatch(this.Address)
} else if regexp.MustCompile(`^(.*):(\d+)$`).MatchString(this.Address) {
var matches = regexp.MustCompile(`^(.*):(\d+)$`).FindStringSubmatch(this.Address)
ip := matches[1]
port := matches[2]
if len(ip) == 0 {
@@ -72,9 +74,9 @@ func (this *HTTPFastcgiConfig) Init() error {
}
this.network = "tcp"
this.address = ip + ":" + port
} else if regexp.MustCompile("^\\d+\\.\\d+.\\d+.\\d+$").MatchString(this.Address) {
} else if net.ParseIP(this.address) != nil {
this.network = "tcp"
this.address = this.Address + ":9000"
this.address = configutils.QuoteIP(this.Address) + ":9000"
} else if regexp.MustCompile("^unix:(.+)$").MatchString(this.Address) {
matches := regexp.MustCompile("^unix:(.+)$").FindStringSubmatch(this.Address)
path := matches[1]

View File

@@ -301,13 +301,13 @@ func (this *HTTPLocationConfig) Match(path string, formatter func(source string)
if this.patternType == HTTPLocationPatternTypeExact {
if this.reverse {
if this.caseInsensitive {
return nil, strings.ToLower(path) != strings.ToLower(this.path)
return nil, !strings.EqualFold(path, this.path)
} else {
return nil, path != this.path
}
} else {
if this.caseInsensitive {
return nil, strings.ToLower(path) == strings.ToLower(this.path)
return nil, strings.EqualFold(path, this.path)
} else {
return nil, path == this.path
}

View File

@@ -20,7 +20,7 @@ type MetricItemConfig struct {
Version int32 `yaml:"version" json:"version"`
ExpiresPeriod int `yaml:"expiresPeriod" json:"expiresPeriod"` // 过期周期
sumType string // 统计类型
//sumType string // 统计类型
baseTime time.Time // 基准时间
hasHTTPConnectionValue bool // 是否有统计HTTP连接数的数值
}

View File

@@ -66,8 +66,8 @@ type OriginConfig struct {
requestPath string
requestArgs string
hasRequestHeaders bool
hasResponseHeaders bool
//hasRequestHeaders bool
//hasResponseHeaders bool
uniqueKey string

View File

@@ -1,13 +1,16 @@
package serverconfigs
import "testing"
import (
"context"
"testing"
)
func TestOriginConfig_UniqueKey(t *testing.T) {
origin := &OriginConfig{
Id: 1,
Version: 101,
}
err := origin.Init(nil)
err := origin.Init(context.TODO())
if err != nil {
t.Fatal(err)
}

View File

@@ -53,9 +53,9 @@ type ReverseProxyConfig struct {
schedulingGroupMap map[string]*SchedulingGroup // domain => *SchedulingGroup
schedulingLocker sync.RWMutex
addXRealIPHeader bool
addXForwardedForHeader bool
addForwardedHeader bool
addXRealIPHeader bool
addXForwardedForHeader bool
//addForwardedHeader bool
addXForwardedByHeader bool
addXForwardedHostHeader bool
addXForwardedProtoHeader bool
@@ -131,12 +131,8 @@ func (this *ReverseProxyConfig) Init(ctx context.Context) error {
if domain == "" {
continue
}
for _, origin := range defaultGroup.PrimaryOrigins {
group.PrimaryOrigins = append(group.PrimaryOrigins, origin)
}
for _, origin := range defaultGroup.BackupOrigins {
group.BackupOrigins = append(group.BackupOrigins, origin)
}
group.PrimaryOrigins = append(group.PrimaryOrigins, defaultGroup.PrimaryOrigins...)
group.BackupOrigins = append(group.BackupOrigins, defaultGroup.BackupOrigins...)
}
}
}

View File

@@ -3,6 +3,7 @@
package serverconfigs
import (
"context"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"testing"
)
@@ -30,7 +31,7 @@ func TestReverseProxyConfig_Init(t *testing.T) {
Addr: &NetworkAddressConfig{Host: "127.0.0.4"},
IsOn: true,
})
err := config.Init(nil)
err := config.Init(context.TODO())
if err != nil {
t.Fatal(err)
}

View File

@@ -52,7 +52,7 @@ func (this *RoundRobinScheduling) Next(call *shared.RequestCall) CandidateInterf
if this.index > this.count-1 {
this.index = 0
}
weight := this.currentWeights[this.index]
var weight = this.currentWeights[this.index]
// 已经一轮了,则重置状态
if weight == 0 {
@@ -60,11 +60,10 @@ func (this *RoundRobinScheduling) Next(call *shared.RequestCall) CandidateInterf
this.currentWeights = append([]uint{}, this.rawWeights...)
}
this.index = 0
weight = this.currentWeights[this.index]
}
c := this.Candidates[this.index]
this.currentWeights[this.index] --
this.currentWeights[this.index]--
this.index++
return c
}

View File

@@ -271,7 +271,7 @@ func (this *ServerConfig) Init(ctx context.Context) (results []error) {
this.isOk = true
return nil
return
}
func (this *ServerConfig) IsInitialized() bool {

View File

@@ -1,6 +1,9 @@
package serverconfigs
import "testing"
import (
"context"
"testing"
)
func TestServerConfig_Protocols(t *testing.T) {
{
@@ -65,7 +68,7 @@ func TestServerConfig_Protocols(t *testing.T) {
},
},
}}
err := server.Init(nil)
err := server.Init(context.TODO())
if err != nil {
t.Fatal(err)
}

View File

@@ -214,12 +214,12 @@ func (this *HTTPRequestCond) match(formatter func(source string) string) bool {
return types.Int64(paramValue)%100 == types.Int64(this.Value)
case RequestCondOperatorEqString:
if this.IsCaseInsensitive {
return strings.ToUpper(paramValue) == strings.ToUpper(this.Value)
return strings.EqualFold(paramValue, this.Value)
}
return paramValue == this.Value
case RequestCondOperatorNeqString:
if this.IsCaseInsensitive {
return strings.ToUpper(paramValue) != strings.ToUpper(this.Value)
return !strings.EqualFold(paramValue, this.Value)
}
return paramValue != this.Value
case RequestCondOperatorHasPrefix:
@@ -243,11 +243,11 @@ func (this *HTTPRequestCond) match(formatter func(source string) string) bool {
}
return !strings.Contains(paramValue, this.Value)
case RequestCondOperatorEqIP:
ip := net.ParseIP(paramValue)
var ip = net.ParseIP(paramValue)
if ip == nil {
return false
}
return this.isIP && bytes.Compare(this.ipValue, ip) == 0
return this.isIP && ip.Equal(this.ipValue)
case RequestCondOperatorGtIP:
ip := net.ParseIP(paramValue)
if ip == nil {

View File

@@ -9,5 +9,5 @@ var (
RegexpAllDigitNumber = regexp.MustCompile(`^[+-]?\d+$`) // 整数,支持正负数
RegexpAllFloatNumber = regexp.MustCompile(`^[+-]?\d+(\.\d+)?$`) // 浮点数支持正负数不支持e
RegexpExternalURL = regexp.MustCompile("(?i)^(http|https|ftp)://") // URL
RegexpNamedVariable = regexp.MustCompile("\\${[\\w.-]+}") // 命名变量
RegexpNamedVariable = regexp.MustCompile(`\${[\w.-]+}`) // 命名变量
)

View File

@@ -1,17 +1,21 @@
package shared
package shared_test
import (
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/iwind/TeaGo/assert"
"testing"
)
func TestRegexp(t *testing.T) {
a := assert.NewAssertion(t)
var a = assert.NewAssertion(t)
a.IsTrue(RegexpFloatNumber.MatchString("123"))
a.IsTrue(RegexpFloatNumber.MatchString("123.456"))
a.IsFalse(RegexpFloatNumber.MatchString(".456"))
a.IsFalse(RegexpFloatNumber.MatchString("abc"))
a.IsFalse(RegexpFloatNumber.MatchString("123."))
a.IsFalse(RegexpFloatNumber.MatchString("123.456e7"))
a.IsTrue(shared.RegexpFloatNumber.MatchString("123"))
a.IsTrue(shared.RegexpFloatNumber.MatchString("123.456"))
a.IsFalse(shared.RegexpFloatNumber.MatchString(".456"))
a.IsFalse(shared.RegexpFloatNumber.MatchString("abc"))
a.IsFalse(shared.RegexpFloatNumber.MatchString("123."))
a.IsFalse(shared.RegexpFloatNumber.MatchString("123.456e7"))
a.IsTrue(shared.RegexpNamedVariable.MatchString("${abc.efg}"))
a.IsTrue(shared.RegexpNamedVariable.MatchString("${abc}"))
a.IsFalse(shared.RegexpNamedVariable.MatchString("{abc.efg}"))
}

View File

@@ -252,7 +252,7 @@ func (this *SSLPolicy) certIsEqual(cert1 tls.Certificate, cert2 tls.Certificate)
}
for index, b := range b1 {
if bytes.Compare(b, b2[index]) != 0 {
if !bytes.Equal(b, b2[index]) {
return false
}
}

View File

@@ -3,6 +3,7 @@
package sslconfigs_test
import (
"context"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/sslconfigs"
"github.com/iwind/TeaGo/assert"
"testing"
@@ -120,7 +121,7 @@ Z3NIV2eNt6YBwkC69DzdazXT
OCSPExpiresAt: nowTime + 2,
})
err := policy.Init(nil)
err := policy.Init(context.TODO())
if err != nil {
t.Fatal(err)
}