main.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // example of HTTP server that uses the captcha package.
  2. package main
  3. import (
  4. "fmt"
  5. "github.com/dchest/captcha"
  6. "http"
  7. "template"
  8. )
  9. var formTemplate = template.MustParse(formTemplateSrc, nil)
  10. func showFormHandler(w http.ResponseWriter, r *http.Request) {
  11. d := struct{ CaptchaId string }{captcha.New(captcha.StdLength)}
  12. if err := formTemplate.Execute(w, &d); err != nil {
  13. http.Error(w, err.String(), http.StatusInternalServerError)
  14. }
  15. }
  16. func processFormHandler(w http.ResponseWriter, r *http.Request) {
  17. if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
  18. fmt.Fprintf(w, "Wrong captcha solution! No robots allowed!")
  19. return
  20. }
  21. fmt.Fprintf(w, "Great job, human! You solved the captcha.")
  22. }
  23. func main() {
  24. http.HandleFunc("/", showFormHandler)
  25. http.HandleFunc("/process", processFormHandler)
  26. http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
  27. http.ListenAndServe(":8080", nil)
  28. }
  29. const formTemplateSrc = `
  30. <form action="/process" method=post>
  31. <p>Type the numbers you see in the picture below:</p>
  32. <p><img src="/captcha/{CaptchaId}.png" alt="Captcha image"></p>
  33. <a href="#" onclick="var e=getElementById('audio'); e.display=true; e.play(); return false">Play Audio</a>
  34. <audio id=audio controls style="display:none">
  35. <source src="/captcha/{CaptchaId}.wav" type="audio/x-wav">
  36. You browser doesn't support audio.
  37. <a href="/captcha/{CaptchaId}.wav?get">Download file</a> to play it in the external player.
  38. </audio>
  39. <input type=hidden name=captchaId value={CaptchaId}><br>
  40. <input name=captchaSolution>
  41. <input type=submit>
  42. `