captcha.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package servers
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/dchest/captcha"
  6. "net/http"
  7. "path"
  8. "strings"
  9. "time"
  10. )
  11. // 这里需要自行实现captcha 的gin模式
  12. func GinCapthcaServeHTTP(w http.ResponseWriter, r *http.Request) {
  13. dir, file := path.Split(r.URL.Path)
  14. ext := path.Ext(file)
  15. id := file[:len(file)-len(ext)]
  16. if ext == "" || id == "" {
  17. http.NotFound(w, r)
  18. return
  19. }
  20. fmt.Println("reload : " + r.FormValue("reload"))
  21. if r.FormValue("reload") != "" {
  22. captcha.Reload(id)
  23. }
  24. lang := strings.ToLower(r.FormValue("lang"))
  25. download := path.Base(dir) == "download"
  26. if Serve(w, r, id, ext, lang, download, 120, 40) == captcha.ErrNotFound {
  27. http.NotFound(w, r)
  28. }
  29. }
  30. func Serve(w http.ResponseWriter, r *http.Request, id, ext, lang string, download bool, width, height int) error {
  31. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  32. w.Header().Set("Pragma", "no-cache")
  33. w.Header().Set("Expires", "0")
  34. var content bytes.Buffer
  35. switch ext {
  36. case ".png":
  37. w.Header().Set("Content-Type", "image/png")
  38. captcha.WriteImage(&content, id, width, height)
  39. case ".wav":
  40. w.Header().Set("Content-Type", "audio/x-wav")
  41. captcha.WriteAudio(&content, id, lang)
  42. default:
  43. return captcha.ErrNotFound
  44. }
  45. if download {
  46. w.Header().Set("Content-Type", "application/octet-stream")
  47. }
  48. http.ServeContent(w, r, id+ext, time.Time{}, bytes.NewReader(content.Bytes()))
  49. return nil
  50. }