all repos — captcha @ 90e4f7499bd2ad1e8c4e92fb54e97d79fc53e6b5

Go package captcha implements generation and verification of image and audio CAPTCHAs.

newStore: accept collectNum and expiration time.

Prevoiusly, Expiration and CollectNum were hard-coded into store.go.
This change moves these constants to captcha.go (renaming to Std*), and
makes newStore accept them as arguments.

This will enable setting these paraments by package users sometime in
the future, if needed, and also allows testing of the store garbage
collection.
Dmitry Chestnykh dmitry@codingrobots.com
Sun, 24 Apr 2011 15:19:49 +0200
commit

90e4f7499bd2ad1e8c4e92fb54e97d79fc53e6b5

parent

9de0d066b9199eb378005dfef151c0dcfb81da7f

2 files changed, 24 insertions(+), 17 deletions(-)

jump to
M captcha.gocaptcha.go

@@ -8,12 +8,20 @@ "io"

"os" ) -// Standard number of digits in captcha. -const StdLength = 6 +const ( + // Standard number of digits in captcha. + StdLength = 6 + // The number of captchas created that triggers garbage collection + StdCollectNum = 100 + // Expiration time of captchas + StdExpiration = 2*60 // 2 minutes + +) var ErrNotFound = os.NewError("captcha with the given id not found") -var globalStore = newStore() +// globalStore is a shared storage for captchas, generated by New function. +var globalStore = newStore(StdCollectNum, StdExpiration) // RandomDigits returns a byte slice of the given length containing random // digits in range 0-9.
M store.gostore.go

@@ -6,13 +6,6 @@ "sync"

"time" ) -const ( - // Expiration time for captchas - Expiration = 2 * 60 // 2 minutes - // The number of captchas created that triggers garbage collection - CollectNum = 100 -) - // expValue stores timestamp and id of captchas. It is used in a list inside // store for indexing generated captchas by timestamp to enable garbage // collection of expired captchas.

@@ -26,15 +19,21 @@ type store struct {

mu sync.RWMutex ids map[string][]byte exp *list.List - // Number of items stored after last collection - colNum int + // Number of items stored after last collection. + numStored int + // Number of saved items that triggers collection. + collectNum int + // Expiration time of captchas. + expiration int64 } // newStore initializes and returns a new store. -func newStore() *store { +func newStore(collectNum int, expiration int64) *store { s := new(store) s.ids = make(map[string][]byte) s.exp = list.New() + s.collectNum = collectNum + s.expiration = expiration return s }

@@ -44,10 +43,10 @@ s.mu.Lock()

defer s.mu.Unlock() s.ids[id] = digits s.exp.PushBack(expValue{time.Seconds(), id}) - s.colNum++ - if s.colNum > CollectNum { + s.numStored++ + if s.numStored > s.collectNum { go s.collect() - s.colNum = 0 + s.numStored = 0 } }

@@ -85,7 +84,7 @@ ev, ok := e.Value.(expValue)

if !ok { return } - if ev.timestamp+Expiration < now { + if ev.timestamp+s.expiration < now { s.ids[ev.id] = nil, false s.exp.Remove(e) } else {