filter.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package fsw
  2. import (
  3. "strings"
  4. )
  5. const (
  6. REPLTXT = "**************************************************************************"
  7. )
  8. //过滤,验证是否存在敏感词
  9. func Match(txt string) bool {
  10. for i := 0; i < len(txt); i++ {
  11. nowMap := &link
  12. length := 0 // 匹配标识数默认为0
  13. flag := false // 敏感词结束标识位:用于敏感词只有1位的情况
  14. for j := i; j < len(txt); j++ {
  15. word := txt[j : j+1]
  16. nowMap, _ = (*nowMap)[word].(*map[string]interface{})
  17. if nowMap != nil {
  18. length = length + 1
  19. tag, _ := (*nowMap)["YN"].(string)
  20. if "Y" == tag {
  21. flag = true
  22. return true
  23. }
  24. } else {
  25. break
  26. }
  27. }
  28. if length < 2 || !flag {
  29. length = 0
  30. }
  31. if length > 0 {
  32. //log.Println(txt[i : i+length])
  33. i = i + length - 1
  34. }
  35. }
  36. return false
  37. }
  38. //替换
  39. func Repl(atxt ...string) string {
  40. txt := atxt[0]
  41. repl := ""
  42. if len(atxt) == 2 {
  43. repl = atxt[1]
  44. }
  45. keywords := []string{}
  46. for i := 0; i < len(txt); i++ {
  47. nowMap := &link
  48. length := 0 // 匹配标识数默认为0
  49. flag := false // 敏感词结束标识位:用于敏感词只有1位的情况
  50. for j := i; j < len(txt); j++ {
  51. word := txt[j : j+1]
  52. nowMap, _ = (*nowMap)[word].(*map[string]interface{})
  53. if nowMap != nil {
  54. length = length + 1
  55. tag, _ := (*nowMap)["YN"].(string)
  56. if "Y" == tag {
  57. flag = true
  58. }
  59. } else {
  60. break
  61. }
  62. }
  63. if length < 2 || !flag {
  64. length = 0
  65. }
  66. if length > 0 {
  67. keywords = append(keywords, txt[i:i+length])
  68. i = i + length - 1
  69. }
  70. }
  71. for _, keyword := range keywords {
  72. if len(atxt) == 1 {
  73. txt = strings.Replace(txt, keyword, REPLTXT[:len([]rune(keyword))], -1)
  74. } else {
  75. txt = strings.Replace(txt, keyword, repl, -1)
  76. }
  77. }
  78. return txt
  79. }