all repos

onasty @ a4b3d8e5246c848a66cc27013e6aeb22d1660da2

a one-time notes service
1 files changed, 17 insertions(+), 3 deletions(-)
refactor(mailer): add mutex to testing mailer, to avoid race-conditions (#27)

Author: Smirnov Oleksandr ss2316544@gmail.com
Committed by: GitHub noreply@github.com
Committed at: 2024-10-03 22:31:39 +0300
Parent: 304505a
M internal/mailer/testing_mailer.go
···
        1
        1
         package mailer

      
        2
        2
         

      
        3
        
        -import "context"

      
        
        3
        +import (

      
        
        4
        +	"context"

      
        
        5
        +	"sync"

      
        
        6
        +)

      
        4
        7
         

      
        5
        8
         var _ Mailer = (*TestMailer)(nil)

      
        6
        9
         

      
        7
        10
         type TestMailer struct {

      
        
        11
        +	mu sync.Mutex

      
        
        12
        +

      
        8
        13
         	emails map[string]string

      
        9
        14
         }

      
        10
        15
         

      ···
        12
        17
         // that implementation of Mailer stores all sent email in memory

      
        13
        18
         // to get the last email sent to a specific email use GetLastSentEmailToEmail

      
        14
        19
         func NewTestMailer() *TestMailer {

      
        15
        
        -	return &TestMailer{

      
        
        20
        +	return &TestMailer{ //nolint:exhaustruct

      
        16
        21
         		emails: make(map[string]string),

      
        17
        22
         	}

      
        18
        23
         }

      
        19
        24
         

      
        20
        25
         func (t *TestMailer) Send(_ context.Context, to, _, content string) error {

      
        
        26
        +	t.mu.Lock()

      
        
        27
        +	defer t.mu.Unlock()

      
        
        28
        +

      
        21
        29
         	t.emails[to] = content

      
        
        30
        +

      
        22
        31
         	return nil

      
        23
        32
         }

      
        24
        33
         

      
        25
        34
         // GetLastSentEmailToEmail returns the last email sent to a specific email

      
        26
        35
         func (t *TestMailer) GetLastSentEmailToEmail(email string) string {

      
        27
        
        -	return t.emails[email]

      
        
        36
        +	t.mu.Lock()

      
        
        37
        +	defer t.mu.Unlock()

      
        
        38
        +

      
        
        39
        +	e := t.emails[email]

      
        
        40
        +

      
        
        41
        +	return e

      
        28
        42
         }