handler.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright 2023 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package msg
  15. import (
  16. "io"
  17. "reflect"
  18. )
  19. func AsyncHandler(f func(Message)) func(Message) {
  20. return func(m Message) {
  21. go f(m)
  22. }
  23. }
  24. // Dispatcher is used to send messages to net.Conn or register handlers for messages read from net.Conn.
  25. type Dispatcher struct {
  26. rw io.ReadWriter
  27. sendCh chan Message
  28. doneCh chan struct{}
  29. msgHandlers map[reflect.Type]func(Message)
  30. defaultHandler func(Message)
  31. }
  32. func NewDispatcher(rw io.ReadWriter) *Dispatcher {
  33. return &Dispatcher{
  34. rw: rw,
  35. sendCh: make(chan Message, 100),
  36. doneCh: make(chan struct{}),
  37. msgHandlers: make(map[reflect.Type]func(Message)),
  38. }
  39. }
  40. // Run will block until io.EOF or some error occurs.
  41. func (d *Dispatcher) Run() {
  42. go d.sendLoop()
  43. go d.readLoop()
  44. }
  45. func (d *Dispatcher) sendLoop() {
  46. for {
  47. select {
  48. case <-d.doneCh:
  49. return
  50. case m := <-d.sendCh:
  51. _ = WriteMsg(d.rw, m)
  52. }
  53. }
  54. }
  55. func (d *Dispatcher) readLoop() {
  56. for {
  57. m, err := ReadMsg(d.rw)
  58. if err != nil {
  59. close(d.doneCh)
  60. return
  61. }
  62. if handler, ok := d.msgHandlers[reflect.TypeOf(m)]; ok {
  63. handler(m)
  64. } else if d.defaultHandler != nil {
  65. d.defaultHandler(m)
  66. }
  67. }
  68. }
  69. func (d *Dispatcher) Send(m Message) error {
  70. select {
  71. case <-d.doneCh:
  72. return io.EOF
  73. case d.sendCh <- m:
  74. return nil
  75. }
  76. }
  77. func (d *Dispatcher) SendChannel() chan Message {
  78. return d.sendCh
  79. }
  80. func (d *Dispatcher) RegisterHandler(msg Message, handler func(Message)) {
  81. d.msgHandlers[reflect.TypeOf(msg)] = handler
  82. }
  83. func (d *Dispatcher) RegisterDefaultHandler(handler func(Message)) {
  84. d.defaultHandler = handler
  85. }
  86. func (d *Dispatcher) Done() chan struct{} {
  87. return d.doneCh
  88. }