优化代码

This commit is contained in:
GoEdgeLab
2023-08-08 15:39:00 +08:00
parent 72c390fba5
commit 2a5aefe7f1
22 changed files with 27 additions and 53 deletions

View File

@@ -662,7 +662,7 @@ func (this *FileListDB) shouldRecover() bool {
var errString = ""
var shouldRecover = false
if result.Next() {
err = result.Scan(&errString)
_ = result.Scan(&errString)
if strings.TrimSpace(errString) != "ok" {
shouldRecover = true
}

View File

@@ -101,6 +101,9 @@ func TestFileListDB_CleanMatchPrefix(t *testing.T) {
}
err = db.Init()
if err != nil {
t.Fatal(err)
}
err = db.CleanMatchPrefix("https://*.goedge.cn/large-text")
if err != nil {

View File

@@ -148,8 +148,7 @@ func (this *Manager) FindPolicy(policyId int64) *serverconfigs.HTTPCachePolicy {
this.locker.RLock()
defer this.locker.RUnlock()
p, _ := this.policyMap[policyId]
return p
return this.policyMap[policyId]
}
// FindStorageWithPolicy 根据策略ID查找存储
@@ -157,8 +156,7 @@ func (this *Manager) FindStorageWithPolicy(policyId int64) StorageInterface {
this.locker.RLock()
defer this.locker.RUnlock()
storage, _ := this.storageMap[policyId]
return storage
return this.storageMap[policyId]
}
// NewStorageWithPolicy 根据策略获取存储对象

View File

@@ -1276,13 +1276,6 @@ func (this *FileStorage) increaseHit(key string, hash string, reader Reader) {
this.hotMapLocker.Lock()
hotItem, ok := this.hotMap[key]
// 限制热点数据存活时间
var unixTime = time.Now().Unix()
var expiresAt = reader.ExpiresAt()
if expiresAt <= 0 || expiresAt > unixTime+HotItemLifeSeconds {
expiresAt = unixTime + HotItemLifeSeconds
}
if ok {
hotItem.Hits++
} else if len(this.hotMap) < HotItemSize { // 控制数量

View File

@@ -8,7 +8,7 @@ import "strings"
func partialRangesFilePath(path string) string {
// ranges路径
var dotIndex = strings.LastIndex(path, ".")
var rangePath = ""
var rangePath string
if dotIndex < 0 {
rangePath = path + "@ranges.cache"
} else {

View File

@@ -19,7 +19,6 @@ func TestAES128CFBMethod_Encrypt(t *testing.T) {
dst = dst[:len(src)]
t.Log("dst:", string(dst))
src = make([]byte, len(src))
src, err = method.Decrypt(dst)
if err != nil {
t.Fatal(err)
@@ -64,7 +63,6 @@ func TestAES128CFBMethod_Encrypt2(t *testing.T) {
for _, dst := range sources {
dst2 := append([]byte{}, dst...)
src2 := make([]byte, len(dst2))
src2, err := method.Decrypt(dst2)
if err != nil {
t.Fatal(err)

View File

@@ -283,7 +283,7 @@ func (this *IPSetAction) runActionSingleIP(action string, listType IPListType, i
return nil
}
var listName = ""
var listName string
var isIPv6 = strings.Contains(item.IpFrom, ":")
switch listType {

View File

@@ -102,7 +102,7 @@ func (this *ActionManager) UpdateActions(actions []*firewallconfigs.FirewallActi
continue
}
instances, _ := this.eventMap[action.EventLevel]
var instances = this.eventMap[action.EventLevel]
instances = append(instances, instance)
this.eventMap[action.EventLevel] = instances
}

View File

@@ -214,7 +214,7 @@ func (this *IPListManager) fetch() (hasNext bool, err error) {
func (this *IPListManager) FindList(listId int64) *IPList {
this.locker.Lock()
list, _ := this.listMap[listId]
var list = this.listMap[listId]
this.locker.Unlock()
return list
}

View File

@@ -48,7 +48,7 @@ func (this *ClientListener) Accept() (net.Conn, error) {
firewalls.DropTemporaryTo(ip, expiresAt)
} else {
if !waf.SharedIPWhiteList.Contains(waf.IPTypeAll, firewallconfigs.FirewallScopeGlobal, 0, ip) {
var ok = false
var ok bool
expiresAt, ok = waf.SharedIPBlackList.ContainsExpires(waf.IPTypeAll, firewallconfigs.FirewallScopeGlobal, 0, ip)
if ok {
canGoNext = false

View File

@@ -34,7 +34,7 @@ func (this *HTTPRequest) doHostRedirect() (blocked bool) {
}
}
var fullURL = ""
var fullURL string
if u.BeforeHasQuery() {
fullURL = this.URL()
} else {
@@ -194,7 +194,7 @@ func (this *HTTPRequest) doHostRedirect() (blocked bool) {
return false
}
var containsPort = false
var containsPort bool
if u.PortsAll {
containsPort = true
} else {

View File

@@ -731,7 +731,6 @@ func (this *HTTPWriter) PrepareCompression(resp *http.Response, size int64) {
}
// compression writer
var err error = nil
compressionWriter, err := compressions.NewWriter(this.writer, compressionType, int(this.compressionConfig.Level))
if err != nil {
remotelogs.Error("HTTP_WRITER", err.Error())

View File

@@ -149,7 +149,7 @@ func BenchmarkRegexp_MatchString(b *testing.B) {
}
func BenchmarkRegexp_MatchString2(b *testing.B) {
var r = regexp.MustCompile("(?i)(onmouseover|onmousemove|onmousedown|onmouseup|onerror|onload|onclick|ondblclick|onkeydown|onkeyup|onkeypress)(\\s|%09|%0A|(\\+|%20))*(=|%3D)")
var r = regexp.MustCompile(`(?i)(onmouseover|onmousemove|onmousedown|onmouseup|onerror|onload|onclick|ondblclick|onkeydown|onkeyup|onkeypress)(\s|%09|%0A|(\+|%20))*(=|%3D)`)
b.ResetTimer()
for i := 0; i < b.N; i++ {

View File

@@ -13,7 +13,6 @@ var SharedCache = NewBigCache()
//
// Piece1 | Piece2 | Piece3 | ...
// [ Item1, Item2, ... ] | ...
//
type Cache struct {
isDestroyed bool
pieces []*Piece
@@ -123,19 +122,11 @@ func (this *Cache) Read(key string) (item *Item) {
return this.pieces[uint64Key%this.countPieces].Read(uint64Key)
}
func (this *Cache) readIntKey(key uint64) (value *Item) {
return this.pieces[key%this.countPieces].Read(key)
}
func (this *Cache) Delete(key string) {
var uint64Key = HashKey([]byte(key))
this.pieces[uint64Key%this.countPieces].Delete(uint64Key)
}
func (this *Cache) deleteIntKey(key uint64) {
this.pieces[key%this.countPieces].Delete(key)
}
func (this *Cache) Count() (count int) {
for _, piece := range this.pieces {
count += piece.Count()

View File

@@ -34,10 +34,7 @@ func IsLocalIP(ipString string) bool {
// IPv6
if strings.Contains(ipString, ":") {
if ip.String() == "::1" {
return true
}
return false
return ip.String() == "::1"
}
// IPv4

View File

@@ -72,7 +72,7 @@ func (this *IntMap[K, V]) Has(k K) bool {
func (this *IntMap[K, V]) Get(k K) (value V) {
var index = this.index(k)
this.lockers[index].RLock()
value, _ = this.m[index][k]
value = this.m[index][k]
this.lockers[index].RUnlock()
return
}

View File

@@ -12,7 +12,7 @@ func setMaxMemory(memoryGB int) {
if memoryGB <= 0 {
memoryGB = 1
}
var maxMemoryBytes int64 = 0
var maxMemoryBytes int64
if memoryGB > 10 {
maxMemoryBytes = int64(memoryGB-2) << 30 // 超过10G内存的允许剩余2G内存
} else {

View File

@@ -85,7 +85,7 @@ func (this *RateLimitWriter) write(p []byte) (n int, err error) {
this.written += n
if this.written >= this.rateBytes {
var duration = 1*time.Second - time.Now().Sub(this.before)
var duration = 1*time.Second - time.Since(this.before)
if duration > 0 {
time.Sleep(duration)
}

View File

@@ -108,10 +108,10 @@ func (this *CaptchaValidator) show(actionConfig *CaptchaAction, req requests.Req
lang = "en-US"
}
var msgTitle = ""
var msgPrompt = ""
var msgButtonTitle = ""
var msgRequestId = ""
var msgTitle string
var msgPrompt string
var msgButtonTitle string
var msgRequestId string
switch lang {
case "en-US":

View File

@@ -40,14 +40,9 @@ func (this *CCCheckpoint) RequestValue(req requests.Request, param string, optio
period = 7 * 86400
}
v, _ := options["userType"]
userType := types.String(v)
v, _ = options["userField"]
userField := types.String(v)
v, _ = options["userIndex"]
userIndex := types.Int(v)
var userType = types.String(options["userType"])
var userField = types.String(options["userField"])
var userIndex = types.Int(options["userIndex"])
if param == "requests" { // requests
var key = ""

View File

@@ -23,7 +23,7 @@ import (
"strings"
)
var singleParamRegexp = regexp.MustCompile("^\\${[\\w.-]+}$")
var singleParamRegexp = regexp.MustCompile(`^\${[\w.-]+}$`)
// Rule
type Rule struct {

View File

@@ -45,7 +45,7 @@ func (this *WAFManager) UpdatePolicies(policies []*firewallconfigs.HTTPFirewallP
// FindWAF 查找WAF
func (this *WAFManager) FindWAF(policyId int64) *WAF {
this.locker.RLock()
w, _ := this.mapping[policyId]
var w = this.mapping[policyId]
this.locker.RUnlock()
return w
}