all repos — captcha @ 307ecdadf152ddf58a2cb7cad101847c2e1814b9

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

example/main.go (view raw)

 1// example of HTTP server that uses the captcha package.
 2package main
 3
 4import (
 5	"github.com/dchest/captcha"
 6	"http"
 7	"io"
 8	"log"
 9	"template"
10)
11
12var formTemplate = template.MustParse(formTemplateSrc, nil)
13
14func showFormHandler(w http.ResponseWriter, r *http.Request) {
15	if r.URL.Path != "/" {
16		http.NotFound(w, r)
17		return
18	}
19	d := struct {
20		CaptchaId  string
21		JavaScript string
22	}{
23		captcha.New(captcha.StdLength),
24		formJavaScript,
25	}
26	if err := formTemplate.Execute(w, &d); err != nil {
27		http.Error(w, err.String(), http.StatusInternalServerError)
28	}
29}
30
31func processFormHandler(w http.ResponseWriter, r *http.Request) {
32	if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
33		io.WriteString(w, "Wrong captcha solution! No robots allowed!\n")
34	} else {
35		io.WriteString(w, "Great job, human! You solved the captcha.\n")
36	}
37	io.WriteString(w, "<br><a href='/'>Try another one</a>")
38}
39
40func main() {
41	http.HandleFunc("/", showFormHandler)
42	http.HandleFunc("/process", processFormHandler)
43	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
44	if err := http.ListenAndServe(":8080", nil); err != nil {
45		log.Fatal(err)
46	}
47}
48
49const formJavaScript = `
50function playAudio() {
51	var e = document.getElementById('audio')
52	e.style.display = 'block';
53	e.play();
54	return false;
55}
56
57function reload() {
58	function setSrcQuery(e, q) {
59		var src  = e.src;
60		var p = src.indexOf('?');
61		if (p >= 0) {
62			src = src.substr(0, p);
63		}
64		e.src = src + "?" + q
65	}
66	setSrcQuery(document.getElementById('image'), "reload=" + (new Date()).getTime());
67	setSrcQuery(document.getElementById('audio'), (new Date()).getTime());
68	return false;
69}
70`
71
72const formTemplateSrc = `<!doctype html>
73<head><title>Captcha Example</title></head>
74<body>
75<script>
76{JavaScript}
77</script>
78<form action="/process" method=post>
79<p>Type the numbers you see in the picture below:</p>
80<p><img id=image src="/captcha/{CaptchaId}.png" alt="Captcha image"></p>
81<a href="#" onclick="reload()">Reload</a> | <a href="#" onclick="playAudio()">Play Audio</a>
82<audio id=audio controls style="display:none" src="/captcha/{CaptchaId}.wav" preload=none>
83  You browser doesn't support audio.
84  <a href="/captcha/download/{CaptchaId}.wav">Download file</a> to play it in the external player.
85</audio>
86<input type=hidden name=captchaId value="{CaptchaId}"><br>
87<input name=captchaSolution>
88<input type=submit value=Submit>
89</form>
90`