chat.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package chat
  2. import (
  3. "context"
  4. "log"
  5. "sync"
  6. "sync/atomic"
  7. "git.ali33.ru/fcg-xvii/rest"
  8. )
  9. func New() *Chat {
  10. res := &Chat{
  11. users: &sync.Map{},
  12. idCounter: &atomic.Int64{},
  13. chConnect: make(chan rest.IStream, 5),
  14. }
  15. go res.work()
  16. return res
  17. }
  18. type Chat struct {
  19. ctx context.Context
  20. cancel context.CancelFunc
  21. users *sync.Map
  22. idCounter *atomic.Int64
  23. chConnect chan rest.IStream
  24. }
  25. func (s *Chat) Close() {
  26. s.cancel()
  27. }
  28. func (s *Chat) work() {
  29. s.ctx, s.cancel = context.WithCancel(context.Background())
  30. for {
  31. select {
  32. case <-s.ctx.Done():
  33. return
  34. case stream := <-s.chConnect:
  35. log.Println("CONNECT-------")
  36. go func() {
  37. <-stream.Context().Done()
  38. log.Println("DISCONNECT-------")
  39. }()
  40. }
  41. }
  42. }
  43. func (s *Chat) Connect() chan<- rest.IStream {
  44. return s.chConnect
  45. }
  46. func (s *Chat) Register(name, password string) *User {
  47. user := &User{
  48. ID: s.idCounter.Add(1),
  49. Name: name,
  50. Password: password,
  51. }
  52. s.users.Store(user.ID, user)
  53. return user
  54. }
  55. func (s *Chat) SearchByID(id int64) (*User, bool) {
  56. if u, check := s.users.Load(id); check {
  57. return u.(*User), true
  58. }
  59. return nil, false
  60. }
  61. func (s *Chat) Auth(name, password string) (res *User, check bool) {
  62. s.users.Range(func(key, val any) bool {
  63. u := val.(*User)
  64. if u.Name == name && u.Password == password {
  65. res, check = u, true
  66. return false
  67. }
  68. return true
  69. })
  70. return
  71. }