You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.5 KiB

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