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