server.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package captcha
  2. import (
  3. "http"
  4. "os"
  5. "path"
  6. "strconv"
  7. )
  8. type captchaHandler struct {
  9. imgWidth int
  10. imgHeight int
  11. }
  12. // Server returns a handler that serves HTTP requests with image or
  13. // audio representations of captchas. Image dimensions are accepted as
  14. // arguments. The server decides which captcha to serve based on the last URL
  15. // path component: file name part must contain a captcha id, file extension —
  16. // its format (PNG or WAV).
  17. //
  18. // For example, for file name "B9QTvDV1RXbVJ3Ac.png" it serves an image captcha
  19. // with id "B9QTvDV1RXbVJ3Ac", and for "B9QTvDV1RXbVJ3Ac.wav" it serves the
  20. // same captcha in audio format.
  21. //
  22. // To serve a captcha as a downloadable file, the URL must be constructed in
  23. // such a way as if the file to serve is in "download" subdirectory:
  24. // "/download/B9QTvDV1RXbVJ3Ac.wav".
  25. //
  26. // To reload captcha (get a different solution for the same captcha id), append
  27. // "?reload=x" to URL, where x may be anything (for example, current time or a
  28. // random number to make browsers refetch an image instead of loading it from
  29. // cache).
  30. func Server(w, h int) http.Handler { return &captchaHandler{w, h} }
  31. func (h *captchaHandler) serve(w http.ResponseWriter, id, ext string, download bool) os.Error {
  32. if download {
  33. w.Header().Set("Content-Type", "application/octet-stream")
  34. }
  35. switch ext {
  36. case ".png":
  37. if !download {
  38. w.Header().Set("Content-Type", "image/png")
  39. }
  40. return WriteImage(w, id, h.imgWidth, h.imgHeight)
  41. case ".wav":
  42. //XXX(dchest) Workaround for Chrome: it wants content-length,
  43. //or else will start playing NOT from the beginning.
  44. //Filed issue: http://code.google.com/p/chromium/issues/detail?id=80565
  45. d := globalStore.Get(id, false)
  46. if d == nil {
  47. return ErrNotFound
  48. }
  49. a := NewAudio(d)
  50. if !download {
  51. w.Header().Set("Content-Type", "audio/x-wav")
  52. }
  53. w.Header().Set("Content-Length", strconv.Itoa(a.EncodedLen()))
  54. _, err := a.WriteTo(w)
  55. return err
  56. }
  57. return ErrNotFound
  58. }
  59. func (h *captchaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  60. dir, file := path.Split(r.URL.Path)
  61. ext := path.Ext(file)
  62. id := file[:len(file)-len(ext)]
  63. if ext == "" || id == "" {
  64. http.NotFound(w, r)
  65. return
  66. }
  67. if r.FormValue("reload") != "" {
  68. Reload(id)
  69. }
  70. download := path.Base(dir) == "download"
  71. if h.serve(w, id, ext, download) == ErrNotFound {
  72. http.NotFound(w, r)
  73. }
  74. // Ignore other errors.
  75. }