Browse Source

Accept the length of the random sequence of numbers.

Dmitry Chestnykh 14 years ago
parent
commit
0674e88f74
2 changed files with 11 additions and 13 deletions
  1. 6 8
      captcha.go
  2. 5 5
      image.go

+ 6 - 8
captcha.go

@@ -17,8 +17,6 @@ const (
 	Expiration = 2 * 60 // 2 minutes
 	// The number of captchas created that triggers garbage collection
 	CollectNum = 100
-	// The number of numbers to use in captcha
-	NumCount = 6
 )
 
 // expValue stores timestamp and id of captchas. It is used in a list inside
@@ -51,8 +49,8 @@ func init() {
 	rand.Seed(time.Seconds())
 }
 
-func randomNumbers() []byte {
-	n := make([]byte, NumCount)
+func randomNumbers(length int) []byte {
+	n := make([]byte, length)
 	if _, err := io.ReadFull(crand.Reader, n); err != nil {
 		panic(err)
 	}
@@ -62,10 +60,10 @@ func randomNumbers() []byte {
 	return n
 }
 
-// New creates a new captcha, saves it in the internal storage, and returns its
-// id.
-func New() string {
-	ns := randomNumbers()
+// New creates a new captcha of the given length, saves it in the internal
+// storage, and returns its id.
+func New(length int) string {
+	ns := randomNumbers(length)
 	id := uniuri.New()
 	store.mu.Lock()
 	defer store.mu.Unlock()

+ 5 - 5
image.go

@@ -55,11 +55,11 @@ func NewImage(numbers []byte, width, height int) *CaptchaImage {
 	return img
 }
 
-// NewRandomImage generates random numbers and returns a new captcha image of
-// the given width and height with those numbers printed on it, and the numbers
-// themselves.
-func NewRandomImage(width, height int) (img *CaptchaImage, numbers []byte) {
-	numbers = randomNumbers()
+// NewRandomImage generates a sequence of random numbers with the given length,
+// and returns a new captcha image of the given width and height with generated
+// numbers printed on it, and the sequence of numbers itself.
+func NewRandomImage(length, width, height int) (img *CaptchaImage, numbers []byte) {
+	numbers = randomNumbers(length)
 	img = NewImage(numbers, width, height)
 	return
 }