main.go 2.2 KB

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