Skip to content

Commit 505ee83

Browse files
[FIX] refactor else usage
1 parent 7499910 commit 505ee83

File tree

9 files changed

+112
-85
lines changed

9 files changed

+112
-85
lines changed

cache/memory.go

Lines changed: 51 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ func (mc *MemoryCache) Get(_ context.Context, key string, dest interface{}) (boo
9595

9696
memItem, ok := element.Value.(*memoryItem)
9797
if !ok {
98+
mc.mutex.Unlock()
9899
mc.updateStats(func(s *Stats) { s.Misses++ })
99100
mc.emitEvent(EventGet, key, nil, nil)
100101
return false, NewCacheError("get", key, errors.New("invalid cache item type"))
@@ -162,6 +163,7 @@ func (mc *MemoryCache) Set(_ context.Context, key string, value interface{}, ttl
162163
TTL: effectiveTTL,
163164
Size: dataSize,
164165
Namespace: mc.config.Namespace,
166+
ExpiresAt: time.Time{}, // Default to no expiration
165167
}
166168

167169
if effectiveTTL > 0 {
@@ -177,7 +179,8 @@ func (mc *MemoryCache) Set(_ context.Context, key string, value interface{}, ttl
177179
defer mc.mutex.Unlock()
178180

179181
// Check if key already exists
180-
if element, exists := mc.items[formattedKey]; exists {
182+
element, exists := mc.items[formattedKey]
183+
if exists {
181184
// Update existing item
182185
oldMemItem, ok := element.Value.(*memoryItem)
183186
if !ok {
@@ -192,20 +195,24 @@ func (mc *MemoryCache) Set(_ context.Context, key string, value interface{}, ttl
192195
mc.updateStats(func(s *Stats) {
193196
s.Memory = s.Memory - oldMemItem.dataSize + dataSize
194197
})
195-
} else {
196-
// Add new item
197-
element := mc.lruList.PushFront(memItem)
198-
mc.items[formattedKey] = element
199198

200-
mc.updateStats(func(s *Stats) {
201-
s.Size++
202-
s.Memory += dataSize
203-
})
199+
mc.updateStats(func(s *Stats) { s.Sets++ })
200+
mc.emitEvent(EventSet, key, value, nil)
201+
return nil
202+
}
204203

205-
// Check if we need to evict items
206-
if mc.config.MaxSize > 0 && mc.stats.Size > mc.config.MaxSize {
207-
mc.evictLRU()
208-
}
204+
// Add new item
205+
element = mc.lruList.PushFront(memItem)
206+
mc.items[formattedKey] = element
207+
208+
mc.updateStats(func(s *Stats) {
209+
s.Size++
210+
s.Memory += dataSize
211+
})
212+
213+
// Check if we need to evict items
214+
if mc.config.MaxSize > 0 && mc.stats.Size > mc.config.MaxSize {
215+
mc.evictLRU()
209216
}
210217

211218
mc.updateStats(func(s *Stats) { s.Sets++ })
@@ -250,17 +257,17 @@ func (mc *MemoryCache) Exists(_ context.Context, key string) (bool, error) {
250257
item := memItem.item
251258

252259
// Check if item has expired
253-
if item.IsExpired() {
260+
if !item.IsExpired() {
254261
mc.mutex.RUnlock()
255-
// Remove expired item
256-
mc.mutex.Lock()
257-
mc.removeElement(element, formattedKey)
258-
mc.mutex.Unlock()
259-
return false, nil
262+
return true, nil
260263
}
261264

262265
mc.mutex.RUnlock()
263-
return true, nil
266+
// Remove expired item
267+
mc.mutex.Lock()
268+
mc.removeElement(element, formattedKey)
269+
mc.mutex.Unlock()
270+
return false, nil
264271
}
265272

266273
// Clear removes all entries from the cache
@@ -364,13 +371,11 @@ func (mc *MemoryCache) SetTTL(_ context.Context, key string, ttl time.Duration)
364371
return NewCacheError("setttl", key, errors.New("invalid item type"))
365372
}
366373
item := memItem.item
367-
374+
item.ExpiresAt = time.Time{}
375+
item.TTL = 0
368376
if ttl > 0 {
369377
item.ExpiresAt = time.Now().Add(ttl)
370378
item.TTL = ttl
371-
} else {
372-
item.ExpiresAt = time.Time{}
373-
item.TTL = 0
374379
}
375380

376381
item.UpdatedAt = time.Now()
@@ -430,17 +435,20 @@ func (mc *MemoryCache) evictLRU() {
430435
}
431436

432437
element := mc.lruList.Back()
433-
if element != nil {
434-
memItem, ok := element.Value.(*memoryItem)
435-
if !ok {
436-
return // Skip if invalid type
437-
}
438-
key := memItem.item.Key
439-
mc.removeElement(element, key)
438+
if element == nil {
439+
return
440+
}
440441

441-
mc.updateStats(func(s *Stats) { s.Evictions++ })
442-
mc.emitEvent(EventEvict, key, nil, nil)
442+
memItem, ok := element.Value.(*memoryItem)
443+
if !ok {
444+
return // Skip if invalid type
443445
}
446+
447+
key := memItem.item.Key
448+
mc.removeElement(element, key)
449+
450+
mc.updateStats(func(s *Stats) { s.Evictions++ })
451+
mc.emitEvent(EventEvict, key, nil, nil)
444452
}
445453

446454
// startCleanup starts the background cleanup goroutine
@@ -478,16 +486,21 @@ func (mc *MemoryCache) cleanupExpired() {
478486
}
479487
item := memItem.item
480488

481-
if !item.ExpiresAt.IsZero() && now.After(item.ExpiresAt) {
482-
expiredKeys = append(expiredKeys, key)
489+
if item.ExpiresAt.IsZero() || !now.After(item.ExpiresAt) {
490+
continue
483491
}
492+
493+
expiredKeys = append(expiredKeys, key)
484494
}
485495

486496
// Remove expired items
487497
for _, key := range expiredKeys {
488-
if element, exists := mc.items[key]; exists {
489-
mc.removeElement(element, key)
490-
mc.emitEvent(EventExpire, key, nil, nil)
498+
element, exists := mc.items[key]
499+
if !exists {
500+
continue
491501
}
502+
503+
mc.removeElement(element, key)
504+
mc.emitEvent(EventExpire, key, nil, nil)
492505
}
493506
}

cache/redis.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,9 @@ func (rc *RedisCache) GetMulti(ctx context.Context, keys []string) (map[string]i
249249
}
250250
result[keys[i]] = dest
251251
rc.updateStats(func(s *Stats) { s.Hits++ })
252+
continue
252253
}
253-
} else {
254+
254255
rc.updateStats(func(s *Stats) { s.Misses++ })
255256
}
256257
}
@@ -334,7 +335,8 @@ func (rc *RedisCache) SetTTL(ctx context.Context, key string, ttl time.Duration)
334335
var err error
335336
if ttl > 0 {
336337
err = rc.client.Expire(ctx, formattedKey, ttl).Err()
337-
} else {
338+
}
339+
if ttl <= 0 {
338340
err = rc.client.Persist(ctx, formattedKey).Err()
339341
}
340342

cache/tiered.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,8 @@ func (tc *TieredCache) GetMulti(ctx context.Context, keys []string) (map[string]
184184
if err != nil {
185185
tc.recordError(err)
186186
// Continue to L2 even if L1 fails
187-
} else {
187+
}
188+
if err == nil {
188189
for key, value := range l1Results {
189190
result[key] = value
190191
}

mail/internal/email/email.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,8 @@ func (e *Email) Bytes() ([]byte, error) {
276276
}
277277

278278
messageWriter = relatedWriter
279-
} else if isRelated && len(htmlAttachments) > 0 {
279+
}
280+
if isRelated && len(htmlAttachments) > 0 {
280281
relatedWriter = w
281282
messageWriter = w
282283
}

mail/security.go

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -57,32 +57,42 @@ func NewSecurityManager(config SecurityConfig) *SecurityManager {
5757
for _, ipStr := range config.IPAllowlist {
5858
if _, network, err := net.ParseCIDR(ipStr); err == nil {
5959
sm.allowedNetworks = append(sm.allowedNetworks, network)
60-
} else if ip := net.ParseIP(ipStr); ip != nil {
61-
// Single IP address - convert to /32 or /128 network
62-
var network *net.IPNet
63-
if ip.To4() != nil {
64-
_, network, _ = net.ParseCIDR(ipStr + "/32")
65-
} else {
66-
_, network, _ = net.ParseCIDR(ipStr + "/128")
67-
}
68-
sm.allowedNetworks = append(sm.allowedNetworks, network)
60+
continue
61+
}
62+
63+
ip := net.ParseIP(ipStr)
64+
if ip == nil {
65+
continue
6966
}
67+
68+
// Single IP address - convert to /32 or /128 network
69+
var network *net.IPNet
70+
_, network, _ = net.ParseCIDR(ipStr + "/128") // Default to IPv6
71+
if ip.To4() != nil {
72+
_, network, _ = net.ParseCIDR(ipStr + "/32") // Override for IPv4
73+
}
74+
sm.allowedNetworks = append(sm.allowedNetworks, network)
7075
}
7176

7277
// Parse IP blocklist
7378
for _, ipStr := range config.IPBlocklist {
7479
if _, network, err := net.ParseCIDR(ipStr); err == nil {
7580
sm.blockedNetworks = append(sm.blockedNetworks, network)
76-
} else if ip := net.ParseIP(ipStr); ip != nil {
77-
// Single IP address - convert to /32 or /128 network
78-
var network *net.IPNet
79-
if ip.To4() != nil {
80-
_, network, _ = net.ParseCIDR(ipStr + "/32")
81-
} else {
82-
_, network, _ = net.ParseCIDR(ipStr + "/128")
83-
}
84-
sm.blockedNetworks = append(sm.blockedNetworks, network)
81+
continue
82+
}
83+
84+
ip := net.ParseIP(ipStr)
85+
if ip == nil {
86+
continue
87+
}
88+
89+
// Single IP address - convert to /32 or /128 network
90+
var network *net.IPNet
91+
_, network, _ = net.ParseCIDR(ipStr + "/128") // Default to IPv6
92+
if ip.To4() != nil {
93+
_, network, _ = net.ParseCIDR(ipStr + "/32") // Override for IPv4
8594
}
95+
sm.blockedNetworks = append(sm.blockedNetworks, network)
8696
}
8797

8898
// Start cleanup goroutine
@@ -143,11 +153,11 @@ func (sm *SecurityManager) ValidateConnection(remoteAddr string) error {
143153
log.Warn().Str("ip", ip.String()).Msg("[Mail] Connection blocked due to authentication failures")
144154
}
145155
return &SecurityError{Type: "auth_blocked", Message: "IP temporarily blocked due to authentication failures"}
146-
} else {
147-
// Reset auth failure tracking after window expires
148-
tracker.blocked = false
149-
tracker.failures = 0
150156
}
157+
158+
// Reset auth failure tracking after window expires
159+
tracker.blocked = false
160+
tracker.failures = 0
151161
}
152162

153163
// Increment connection count

mail/server.go

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,8 @@ func (s *smtpServer) Start(_ context.Context) error {
106106
var err error
107107
if s.config.TLS {
108108
err = s.server.ListenAndServeTLS()
109-
} else {
109+
}
110+
if !s.config.TLS {
110111
err = s.server.ListenAndServe()
111112
}
112113

@@ -276,17 +277,19 @@ func (s *smtpServer) generateSelfSignedCert() (tls.Certificate, error) {
276277
if s.config.CertFile != "" && s.config.KeyFile != "" {
277278
if err := os.MkdirAll(filepath.Dir(s.config.CertFile), 0750); err != nil {
278279
log.Warn().Err(err).Msg("[Mail] Failed to create certificate directory")
279-
} else {
280-
if err := os.WriteFile(s.config.CertFile, certPEM.Bytes(), 0600); err != nil {
281-
log.Warn().Err(err).Msg("[Mail] Failed to save certificate file")
282-
}
280+
goto createTLS
281+
}
282+
283+
if err := os.WriteFile(s.config.CertFile, certPEM.Bytes(), 0600); err != nil {
284+
log.Warn().Err(err).Msg("[Mail] Failed to save certificate file")
285+
}
283286

284-
if err := os.WriteFile(s.config.KeyFile, keyPEM.Bytes(), 0600); err != nil {
285-
log.Warn().Err(err).Msg("[Mail] Failed to save key file")
286-
}
287+
if err := os.WriteFile(s.config.KeyFile, keyPEM.Bytes(), 0600); err != nil {
288+
log.Warn().Err(err).Msg("[Mail] Failed to save key file")
287289
}
288290
}
289291

292+
createTLS:
290293
// Create TLS certificate
291294
cert, err := tls.X509KeyPair(certPEM.Bytes(), keyPEM.Bytes())
292295
if err != nil {

mail/template.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -266,14 +266,14 @@ func (tm *TemplateManager) loadTemplateFromDisk(name string) (*template.Template
266266
case tm.config.TemplatesPath != "":
267267
// Try to load from custom path
268268
customPath := filepath.Clean(filepath.Join(tm.config.TemplatesPath, name))
269-
if _, err := os.Stat(customPath); err == nil {
270-
content, err = os.ReadFile(customPath)
271-
if err != nil {
272-
return nil, apperror.NewError("failed to read template file").AddError(err)
273-
}
274-
} else {
269+
if _, err := os.Stat(customPath); err != nil {
275270
return nil, apperror.NewError("template not found in templates path").AddError(err)
276271
}
272+
273+
content, err = os.ReadFile(customPath)
274+
if err != nil {
275+
return nil, apperror.NewError("failed to read template file").AddError(err)
276+
}
277277
default:
278278
return nil, apperror.NewError("no template source configured - use WithFS or WithFileServer")
279279
}

queue/cron.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -429,11 +429,9 @@ func (s *TaskScheduler) calculateNextCronRun(cronSpec string, after time.Time) (
429429
continue
430430
}
431431

432-
startMinute := 0
432+
startMinute := s.findFirstValidValue(expr.Minute)
433433
if year == t.Year() && month == int(t.Month()) && day == t.Day() && hour == t.Hour() {
434434
startMinute = t.Minute()
435-
} else {
436-
startMinute = s.findFirstValidValue(expr.Minute)
437435
}
438436

439437
nextMinute, foundMinute := s.findNextValidValue(expr.Minute, startMinute)
@@ -457,12 +455,10 @@ func (s *TaskScheduler) calculateNextCronRun(cronSpec string, after time.Time) (
457455
}
458456

459457
if expr.Second != nil {
460-
startSecond := 0
458+
startSecond := s.findFirstValidValue(*expr.Second)
461459
if year == t.Year() && month == int(t.Month()) && day == t.Day() &&
462460
hour == t.Hour() && minute == t.Minute() {
463461
startSecond = t.Second()
464-
} else {
465-
startSecond = s.findFirstValidValue(*expr.Second)
466462
}
467463

468464
nextSecond, foundSecond := s.findNextValidValue(*expr.Second, startSecond)

web/router.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,8 @@ func (router *Router) parseIPList(entries []string) ([]*net.IPNet, error) {
424424
if ip := net.ParseIP(entry); ip != nil {
425425
if ip.To4() != nil {
426426
entry += "/32" // Use /32 for IPv4 addresses
427-
} else {
427+
}
428+
if ip.To4() == nil {
428429
entry += "/128" // Use /128 for IPv6 addresses
429430
}
430431
}

0 commit comments

Comments
 (0)