generated from moul/golang-repo-template
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
85 lines (78 loc) · 2.02 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"bufio"
"context"
"flag"
"fmt"
"io"
"math/rand"
"os"
"strings"
"github.com/peterbourgon/ff/v3/ffcli"
"moul.io/captcha/captcha"
"moul.io/srand"
)
func main() {
if err := run(os.Args, os.Stdin); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func run(args []string, inputStream io.Reader) error {
// CLI configuration
var (
fs = flag.NewFlagSet("generate-fake-data", flag.ExitOnError)
seed = fs.Int64("seed", 0, "random seed (0 means automatic)")
maxRetries = fs.Uint64("retries", 3, "failures allowed (0 means unlimited)")
engineChoice = fs.String("engine", "random", "captcha engine to use (banner, math, random by default)")
)
root := &ffcli.Command{
Name: "captcha [FLAGS]",
FlagSet: fs,
Exec: func(ctx context.Context, args []string) error {
if len(args) > 0 {
return flag.ErrHelp
}
if *seed != 0 {
rand.Seed(*seed)
} else {
rand.Seed(srand.Fast())
}
// init captcha and print the question
var engine captcha.Captcha
switch *engineChoice {
case "math":
engine = captcha.NewMathCaptcha()
case "banner":
engine = captcha.NewBannerCaptcha()
case "random":
engine = captcha.NewRandomCaptcha()
default:
return fmt.Errorf("undefined captcha engine: %q", *engineChoice) // nolint:goerr113
}
question, err := engine.Question()
if err != nil {
return fmt.Errorf("init captcha: %w", err)
}
fmt.Println(question)
// read and check the user input
reader := bufio.NewReader(inputStream)
for i := uint64(0); *maxRetries == 0 || i < *maxRetries; i++ {
fmt.Print("-> ")
text, _ := reader.ReadString('\n')
// convert CRLF to LF
text = strings.ReplaceAll(text, "\n", "")
valid, err := engine.Validate(text)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
continue
}
if valid {
return nil
}
}
return fmt.Errorf("too many failures") // nolint:goerr113
},
}
return root.ParseAndRun(context.Background(), args[1:])
}