main.go 2.3 KB

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