Embed sync.Mutex in CaptchaDB struct in order to directly call its methods.

This commit is contained in:
Alexander Andreev 2022-06-27 01:03:28 +04:00
parent b65f3be236
commit b0d5f9d9d0
Signed by: Arav
GPG Key ID: 0388CC8FAA51063F

View File

@ -37,7 +37,7 @@ type ICaptchaDB interface {
type CaptchaDB struct { type CaptchaDB struct {
DB map[ID]ICaptcha DB map[ID]ICaptcha
ExpireIn time.Duration ExpireIn time.Duration
mut sync.Mutex sync.Mutex
} }
// SetExpiry stores expire value and starts a goroutine // SetExpiry stores expire value and starts a goroutine
@ -68,8 +68,8 @@ func (cdb *CaptchaDB) SetExpiry(expire time.Duration) {
func (cdb *CaptchaDB) New(data string, captcha ICaptcha) (ICaptcha, ID) { func (cdb *CaptchaDB) New(data string, captcha ICaptcha) (ICaptcha, ID) {
id := NewID(data, captcha.GetAnswer()) id := NewID(data, captcha.GetAnswer())
cdb.mut.Lock() cdb.Lock()
defer cdb.mut.Unlock() defer cdb.Unlock()
cdb.DB[id] = captcha cdb.DB[id] = captcha
return captcha, id return captcha, id
@ -86,8 +86,8 @@ func (cdb *CaptchaDB) Image(id ID) (*image.Image, error) {
// Solve compares given answer with a stored one and if failed // Solve compares given answer with a stored one and if failed
// deletes a captcha from database. // deletes a captcha from database.
func (cdb *CaptchaDB) Solve(id ID, answer Answer) (bool, error) { func (cdb *CaptchaDB) Solve(id ID, answer Answer) (bool, error) {
cdb.mut.Lock() cdb.Lock()
defer cdb.mut.Unlock() defer cdb.Unlock()
if c, ok := cdb.DB[id]; ok { if c, ok := cdb.DB[id]; ok {
ok = c.Solve(answer) ok = c.Solve(answer)
if !ok { if !ok {
@ -101,8 +101,8 @@ func (cdb *CaptchaDB) Solve(id ID, answer Answer) (bool, error) {
// IsSolved checks if captcha was solved and removes it // IsSolved checks if captcha was solved and removes it
// from a database. // from a database.
func (cdb *CaptchaDB) IsSolved(id ID) (bool, error) { func (cdb *CaptchaDB) IsSolved(id ID) (bool, error) {
cdb.mut.Lock() cdb.Lock()
defer cdb.mut.Unlock() defer cdb.Unlock()
if c, ok := cdb.DB[id]; ok { if c, ok := cdb.DB[id]; ok {
ok = c.IsSolved() ok = c.IsSolved()
delete(cdb.DB, id) delete(cdb.DB, id)