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 {
15 CaptchaId string
16 JavaScript string
17 }{
18 captcha.New(captcha.StdLength),
19 formJavaScript,
20 }
21 if err := formTemplate.Execute(w, &d); err != nil {
22 http.Error(w, err.String(), http.StatusInternalServerError)
23 }
24}
25
26func processFormHandler(w http.ResponseWriter, r *http.Request) {
27 if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
28 fmt.Fprintf(w, "Wrong captcha solution! No robots allowed!")
29 return
30 }
31 fmt.Fprintf(w, "Great job, human! You solved the captcha.")
32}
33
34func main() {
35 http.HandleFunc("/", showFormHandler)
36 http.HandleFunc("/process", processFormHandler)
37 http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
38 http.ListenAndServe(":8080", nil)
39}
40
41const formJavaScript = `
42function playAudio() {
43 var e = document.getElementById('audio')
44 e.style.display = 'block';
45 e.play();
46 return false;
47}
48
49function reload() {
50 function setSrcQuery(e, q) {
51 var src = e.src;
52 var p = src.indexOf('?');
53 if (p >= 0) {
54 src = src.substr(0, p);
55 }
56 e.src = src + "?" + q
57 }
58 setSrcQuery(document.getElementById('image'), "reload=" + (new Date()).getTime());
59 setSrcQuery(document.getElementById('audio'), (new Date()).getTime());
60 return false;
61}
62`
63
64const formTemplateSrc = `<!doctype html>
65<head><title>Captcha Example</title></head>
66<body>
67<script>
68{JavaScript}
69</script>
70<form action="/process" method=post>
71<p>Type the numbers you see in the picture below:</p>
72<p><img id=image src="/captcha/{CaptchaId}.png" alt="Captcha image"></p>
73<a href="#" onclick="reload()">Reload</a> | <a href="#" onclick="playAudio()">Play Audio</a>
74<audio id=audio controls style="display:none" src="/captcha/{CaptchaId}.wav" preload=none>
75 You browser doesn't support audio.
76 <a href="/captcha/{CaptchaId}.wav?get">Download file</a> to play it in the external player.
77</audio>
78<input type=hidden name=captchaId value="{CaptchaId}"><br>
79<input name=captchaSolution>
80<input type=submit value=Submit>
81</form>
82`