spiderPolyHandler.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package middleware
  2. import (
  3. . "bp.jydev.jianyu360.cn/BaseService/gateway/common/gatecode"
  4. "bp.jydev.jianyu360.cn/BaseService/gateway/common/httpUtil"
  5. "bp.jydev.jianyu360.cn/BaseService/gateway/core/proxy/filterPoly"
  6. "bp.jydev.jianyu360.cn/BaseService/gateway/core/router"
  7. "fmt"
  8. "github.com/gogf/gf/v2/net/ghttp"
  9. "strings"
  10. )
  11. const (
  12. defaultVerifyPageHtml = "default"
  13. VerifyPageHtmlSource = "./resources/antiRes/page/%s.html"
  14. )
  15. var filterPolyManager *filterPoly.Manager
  16. func InitFilterPolyManager() {
  17. filterPolyManager = filterPoly.InitFilterPolyManager()
  18. }
  19. func FilterPolyHandler(r *ghttp.Request) {
  20. ctx := r.GetCtx()
  21. gCtx := router.GetGContext(ctx)
  22. //获取策略
  23. poly := filterPolyManager.GetRule(gCtx.RouterRule.LimitPloy)
  24. status, key := func() (int, string) {
  25. if gCtx.Sess.UserId != "" && poly.Rule.BCheckId { //id请求频率校验
  26. return poly.IdFilter(ctx, gCtx.Sess.UserId)
  27. } else { //ip请求频率校验
  28. return poly.IpFilter(ctx, r.GetClientIp())
  29. }
  30. }()
  31. returnHtml := false
  32. if strings.Contains(strings.ToLower(r.Header.Get("Accept")), "html") {
  33. returnHtml = true
  34. }
  35. //是否开启黑名单
  36. if status == -1 { //黑名单 不响应
  37. r.SetError(NewErrorWithCode(OTHER_ERR_OFTEN, fmt.Sprintf("请求频繁限制")))
  38. r.Response.ResponseWriter.WriteHeader(403)
  39. return
  40. }
  41. if status == 2 { //处理验证码逻辑
  42. rData := poly.VerifyHandle(r.Request, key)
  43. if !returnHtml {
  44. r.Response.WriteJsonExit(rData)
  45. } else {
  46. if renderErr := httpUtil.Render(r.Response.ResponseWriter, getVerifyPage(poly.Rule.VerifyPage), &rData); renderErr != nil {
  47. r.SetError(NewErrorWithCode(GATEWAY_HTML_RENDER_ERR, fmt.Sprintf("验证码页面:%v\n", renderErr)))
  48. }
  49. }
  50. return
  51. }
  52. r.Middleware.Next()
  53. }
  54. //getVerifyPage 获取验证码页面路径
  55. func getVerifyPage(page string) string {
  56. if page != "" {
  57. if strings.HasSuffix(page, ".html") {
  58. page = strings.ReplaceAll(page, ".html", "")
  59. }
  60. return fmt.Sprintf(VerifyPageHtmlSource, page)
  61. } else {
  62. return fmt.Sprintf(VerifyPageHtmlSource, defaultVerifyPageHtml)
  63. }
  64. }