main.go 2.1 KB

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