filter.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package tinymq
  2. import (
  3. "reflect"
  4. "regexp"
  5. "runtime"
  6. "strings"
  7. )
  8. // 一些常用的过滤器
  9. // 匹配所有的频道
  10. func AllChannelFilter() FilterFunc {
  11. return func(conn *Line) (ok bool) {
  12. return true
  13. }
  14. }
  15. // 正则频道过滤器
  16. func RegChannelFilter(channel *regexp.Regexp) FilterFunc {
  17. return func(conn *Line) (ok bool) {
  18. return channel.MatchString(conn.channel)
  19. }
  20. }
  21. // 字符串频道过滤器
  22. func StrChannelFilter(channel string) FilterFunc {
  23. return func(conn *Line) (ok bool) {
  24. return strings.Contains(conn.channel, channel)
  25. }
  26. }
  27. // 开始字符串频道过滤器
  28. func StrPrefixFilter(channel string) FilterFunc {
  29. return func(conn *Line) (ok bool) {
  30. return strings.HasPrefix(conn.channel, channel)
  31. }
  32. }
  33. // 包括名称的频道过滤器
  34. func NamePrefixFilter(name string, channel string) FilterFunc {
  35. c := name + "@" + channel
  36. return func(conn *Line) (ok bool) {
  37. return strings.HasPrefix(conn.channel, c)
  38. }
  39. }
  40. // 包含支名称的频道过滤器
  41. func StrPrefixSubFilter(channel string, substr string) FilterFunc {
  42. return func(conn *Line) (ok bool) {
  43. return strings.HasPrefix(conn.channel, channel) && strings.Contains(conn.channel, substr)
  44. }
  45. }
  46. // 连接过滤器
  47. func LineLinkFilter(line *Line) FilterFunc {
  48. return func(conn *Line) (ok bool) {
  49. return line == conn
  50. }
  51. }
  52. // GetFunctionName returns the fully qualified name of the function passed as an interface.
  53. func GetFunctionName(temp any) string {
  54. // Use reflect to get the pointer to the function's code.
  55. pc := reflect.ValueOf(temp).Pointer()
  56. // Use runtime.FuncForPC to get function details.
  57. f := runtime.FuncForPC(pc)
  58. if f == nil {
  59. return ""
  60. }
  61. return f.Name()
  62. }