Skip to content

Commit

Permalink
Refactor flush to avoid race condition, make code better readable
Browse files Browse the repository at this point in the history
  • Loading branch information
steffenmllr committed Dec 3, 2023
1 parent a2eb923 commit e5e2287
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions analytics/http/http_module.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,27 +151,36 @@ func (l *HttpLogger) isFull() bool {
}

func (l *HttpLogger) flush() {
l.mux.Lock()

if l.eventCount == 0 || l.buffer.Len() == 0 {
l.mux.Unlock()
return
}
l.mux.Lock()
defer l.reset()
defer l.mux.Unlock()

// Close the json array, remove last ,
l.buffer.Truncate(l.buffer.Len() - 1)
_, err := l.buffer.Write([]byte("]"))
if err != nil {
l.reset()
l.mux.Unlock()
glog.Warning("[HttpAnalytics] fail to close the json array")
return
}

payload := make([]byte, l.buffer.Len())
_, err = l.buffer.Read(payload)
if err != nil {
l.reset()
l.mux.Unlock()
glog.Warning("[HttpAnalytics] fail to copy the buffer")
return
}

go l.sender(payload)

l.reset()
l.mux.Unlock()
}

func (l *HttpLogger) reset() {
Expand Down

0 comments on commit e5e2287

Please sign in to comment.