// Copyright 2011 Dmitry Chestnykh. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// example of HTTP server that uses the captcha package.
package main
import (
"fmt"
"github.com/dchest/captcha"
"http"
"io"
"log"
"template"
)
var formTemplate = template.Must(template.New("example").Parse(formTemplateSrc))
func showFormHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
d := struct {
CaptchaId string
}{
captcha.New(),
}
if err := formTemplate.Execute(w, &d); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
}
}
func processFormHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
io.WriteString(w, "Wrong captcha solution! No robots allowed!\n")
} else {
io.WriteString(w, "Great job, human! You solved the captcha.\n")
}
io.WriteString(w, "
Try another one")
}
func main() {
http.HandleFunc("/", showFormHandler)
http.HandleFunc("/process", processFormHandler)
http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
fmt.Println("Server is at localhost:8666")
if err := http.ListenAndServe(":8666", nil); err != nil {
log.Fatal(err)
}
}
const formTemplateSrc = `