node_web.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package core
  2. import (
  3. "sync"
  4. "sync/atomic"
  5. "github.com/dop251/goja"
  6. )
  7. type RR struct {
  8. Req *Request
  9. Res *Response
  10. End func()
  11. }
  12. type HttpListen struct {
  13. Path string
  14. Method string
  15. Chan chan *RR
  16. UUID string
  17. Closed bool
  18. // Handle func(*Request, *Response)
  19. }
  20. var httpListens sync.Map
  21. var httpListensAny sync.Map
  22. var listenCounter2 int64
  23. func AddHttpListen(api, method string, vm *goja.Runtime, uuid string, resolve func(result interface{}), reject func(reason interface{})) {
  24. if method == "ANY" {
  25. var hl *HttpListen
  26. v, ok := httpListensAny.Load(uuid)
  27. if ok {
  28. // logs.Debug("load", uuid)
  29. hl = v.(*HttpListen)
  30. } else {
  31. hl = &HttpListen{
  32. Path: api,
  33. Method: method,
  34. Chan: make(chan *RR, 1000),
  35. }
  36. // logs.Debug("crate", uuid)
  37. httpListensAny.Store(uuid, hl)
  38. }
  39. f, ok := <-hl.Chan
  40. if ok {
  41. // logs.Debug("http resolved")
  42. resolve(f)
  43. } else {
  44. // logs.Debug("script is stopped")
  45. reject(Error(vm, "script is stopped"))
  46. }
  47. return
  48. }
  49. hl := &HttpListen{
  50. Path: api,
  51. Method: method,
  52. UUID: uuid,
  53. }
  54. key := atomic.AddInt64(&listenCounter2, 1)
  55. hl.Chan = make(chan *RR, 1)
  56. httpListens.Store(key, hl)
  57. f, ok := <-hl.Chan
  58. if ok {
  59. resolve(f)
  60. } else {
  61. reject(Error(vm, "script is stopped"))
  62. }
  63. }
  64. func CancelHttpListen(uuid string) {
  65. httpListens.Range(func(key, value any) bool {
  66. hl := value.(*HttpListen)
  67. if hl.UUID == uuid {
  68. httpListens.Delete(key)
  69. if !hl.Closed {
  70. hl.Closed = true
  71. close(hl.Chan)
  72. }
  73. }
  74. return true
  75. })
  76. httpListensAny.Range(func(key, value any) bool {
  77. hl := value.(*HttpListen)
  78. if hl.UUID == uuid {
  79. httpListens.Delete(key)
  80. if !hl.Closed {
  81. hl.Closed = true
  82. close(hl.Chan)
  83. }
  84. }
  85. return true
  86. })
  87. }