go-channel.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package common
  2. import (
  3. "time"
  4. )
  5. func SafeSendBool(ch chan bool, value bool) (closed bool) {
  6. defer func() {
  7. // Recover from panic if one occured. A panic would mean the channel was closed.
  8. if recover() != nil {
  9. closed = true
  10. }
  11. }()
  12. // This will panic if the channel is closed.
  13. ch <- value
  14. // If the code reaches here, then the channel was not closed.
  15. return false
  16. }
  17. func SafeSendString(ch chan string, value string) (closed bool) {
  18. defer func() {
  19. // Recover from panic if one occured. A panic would mean the channel was closed.
  20. if recover() != nil {
  21. closed = true
  22. }
  23. }()
  24. // This will panic if the channel is closed.
  25. ch <- value
  26. // If the code reaches here, then the channel was not closed.
  27. return false
  28. }
  29. // SafeSendStringTimeout send, return true, else return false
  30. func SafeSendStringTimeout(ch chan string, value string, timeout int) (closed bool) {
  31. defer func() {
  32. // Recover from panic if one occured. A panic would mean the channel was closed.
  33. if recover() != nil {
  34. closed = false
  35. }
  36. }()
  37. // This will panic if the channel is closed.
  38. select {
  39. case ch <- value:
  40. return true
  41. case <-time.After(time.Duration(timeout) * time.Second):
  42. return false
  43. }
  44. }