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