refactor: add a rw mutex lock to all getter/setter methods

This commit is contained in:
Derrick Hammer 2024-03-11 17:38:24 -04:00
parent 90d78d310e
commit cd50bf0b39
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 26 additions and 0 deletions

View File

@ -5,6 +5,7 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
"net" "net"
"net/url" "net/url"
"sync"
) )
var ( var (
@ -58,13 +59,18 @@ type BasePeer struct {
socket interface{} socket interface{}
id *encoding.NodeId id *encoding.NodeId
handshaked bool handshaked bool
lock sync.RWMutex
} }
func (b *BasePeer) IsConnected() bool { func (b *BasePeer) IsConnected() bool {
b.lock.RLock()
defer b.lock.RUnlock()
return b.isConnected return b.isConnected
} }
func (b *BasePeer) SetConnected(isConnected bool) { func (b *BasePeer) SetConnected(isConnected bool) {
b.lock.Lock()
defer b.lock.Unlock()
b.isConnected = isConnected b.isConnected = isConnected
} }
@ -99,40 +105,60 @@ func (b *BasePeer) SetIP(ip net.Addr) {
} }
func (b *BasePeer) Challenge() []byte { func (b *BasePeer) Challenge() []byte {
b.lock.RLock()
defer b.lock.RUnlock()
return b.challenge return b.challenge
} }
func (b *BasePeer) SetChallenge(challenge []byte) { func (b *BasePeer) SetChallenge(challenge []byte) {
b.lock.Lock()
defer b.lock.Unlock()
b.challenge = challenge b.challenge = challenge
} }
func (b *BasePeer) Socket() interface{} { func (b *BasePeer) Socket() interface{} {
b.lock.RLock()
defer b.lock.RUnlock()
return b.socket return b.socket
} }
func (b *BasePeer) SetSocket(socket interface{}) { func (b *BasePeer) SetSocket(socket interface{}) {
b.lock.Lock()
defer b.lock.Unlock()
b.socket = socket b.socket = socket
} }
func (b *BasePeer) Id() *encoding.NodeId { func (b *BasePeer) Id() *encoding.NodeId {
b.lock.RLock()
defer b.lock.RUnlock()
return b.id return b.id
} }
func (b *BasePeer) SetId(id *encoding.NodeId) { func (b *BasePeer) SetId(id *encoding.NodeId) {
b.lock.Lock()
defer b.lock.Unlock()
b.id = id b.id = id
} }
func (b *BasePeer) SetConnectionURIs(uris []*url.URL) { func (b *BasePeer) SetConnectionURIs(uris []*url.URL) {
b.lock.Lock()
defer b.lock.Unlock()
b.connectionURIs = uris b.connectionURIs = uris
} }
func (b *BasePeer) ConnectionURIs() []*url.URL { func (b *BasePeer) ConnectionURIs() []*url.URL {
b.lock.RLock()
b.lock.RUnlock()
return b.connectionURIs return b.connectionURIs
} }
func (b *BasePeer) IsHandshakeDone() bool { func (b *BasePeer) IsHandshakeDone() bool {
b.lock.RLock()
defer b.lock.RUnlock()
return b.handshaked return b.handshaked
} }
func (b *BasePeer) SetHandshakeDone(status bool) { func (b *BasePeer) SetHandshakeDone(status bool) {
b.lock.Lock()
defer b.lock.Unlock()
b.handshaked = status b.handshaked = status
} }