generated from moul/golang-repo-template
-
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Manfred Touron <94029+moul@users.noreply.github.com>
- Loading branch information
Showing
2 changed files
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package captcha | ||
|
||
import ( | ||
"fmt" | ||
"math/rand" | ||
"strconv" | ||
"strings" | ||
) | ||
|
||
type mathCaptcha struct { | ||
equation string | ||
result int | ||
} | ||
|
||
func NewMathCaptcha() Captcha { | ||
a := rand.Intn(5) + 1 // nolint:gosec,gomnd | ||
b := rand.Intn(5) + 1 // nolint:gosec,gomnd | ||
equation := fmt.Sprintf("%d + %d", a, b) | ||
result := a + b | ||
return mathCaptcha{equation, result} | ||
} | ||
|
||
func (c mathCaptcha) Question() (string, error) { | ||
return c.equation, nil | ||
} | ||
|
||
func (c mathCaptcha) Validate(input string) (bool, error) { | ||
input = strings.TrimSpace(input) | ||
if input == "" { | ||
return false, nil | ||
} | ||
nb, err := strconv.Atoi(input) | ||
if err != nil { | ||
return false, fmt.Errorf("invalid input: %w", err) | ||
} | ||
return nb == c.result, nil | ||
} | ||
|
||
var _ Captcha = (*mathCaptcha)(nil) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package captcha_test | ||
|
||
import ( | ||
"fmt" | ||
"math/rand" | ||
|
||
"moul.io/captcha/captcha" | ||
) | ||
|
||
func ExampleNewMathCaptcha() { | ||
rand.Seed(42) | ||
captcha := captcha.NewMathCaptcha() | ||
question, _ := captcha.Question() | ||
fmt.Println(question) | ||
|
||
valid, _ := captcha.Validate("42") | ||
fmt.Println(valid) | ||
|
||
valid, _ = captcha.Validate("lorem ipsum") | ||
fmt.Println(valid) | ||
|
||
valid, _ = captcha.Validate("1 + 3") | ||
fmt.Println(valid) | ||
|
||
valid, _ = captcha.Validate("4") | ||
fmt.Println(valid) | ||
|
||
valid, _ = captcha.Validate("\n 4\t \n\n \t") | ||
fmt.Println(valid) | ||
|
||
// Output: | ||
// 1 + 3 | ||
// false | ||
// false | ||
// false | ||
// true | ||
// true | ||
} |