all repos — captcha @ a9e88462c0b1e354e0f39c1a55021efbce728c7b

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	"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	if err := formTemplate.Execute(w, &d); err != nil {
16		http.Error(w, err.String(), http.StatusInternalServerError)
17	}
18}
19
20func processFormHandler(w http.ResponseWriter, r *http.Request) {
21	if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
22		fmt.Fprintf(w, "Wrong captcha solution! No robots allowed!")
23		return
24	}
25	fmt.Fprintf(w, "Great job, human! You solved the captcha.")
26}
27
28func main() {
29	http.HandleFunc("/", showFormHandler)
30	http.HandleFunc("/process", processFormHandler)
31	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
32	http.ListenAndServe(":8080", nil)
33}
34
35const formTemplateSrc = `
36<form action="/process" method=post>
37<p>Type the numbers you see in the picture below:</p>
38<p><img src="/captcha/{CaptchaId}.png" alt="Captcha image"></p>
39<a href="#" onclick="var e=getElementById('audio'); e.display=true; e.play(); return false">Play Audio</a>
40<audio id=audio controls style="display:none">
41  <source src="/captcha/{CaptchaId}.wav" type="audio/x-wav">
42  You browser doesn't support audio.
43  <a href="/captcha/{CaptchaId}.wav?get">Download file</a> to play it in the external player.
44</audio>
45<input type=hidden name=captchaId value={CaptchaId}><br>
46<input name=captchaSolution>
47<input type=submit>
48`