all repos — captcha @ 34dcf8d144dd8c7323d3abdefa08b46d05abc4f3

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