broadcast.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package dm
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "time"
  9. model "go-common/app/job/main/activity/model/dm"
  10. "go-common/library/log"
  11. )
  12. // Broadcast dm broadcast.
  13. func (d *Dao) Broadcast(c context.Context, dm *model.Broadcast) (err error) {
  14. var (
  15. b []byte
  16. req *http.Request
  17. res struct {
  18. Code int64 `json:"code"`
  19. }
  20. )
  21. url := fmt.Sprintf("%s?cids=%d", d.broadcastURL, dm.RoomID)
  22. for i := 0; i < 50; i++ {
  23. if b, err = json.Marshal(dm); err != nil {
  24. log.Error("json.Marshal(%+v) error(%v)", dm, err)
  25. return
  26. }
  27. req, err = http.NewRequest("POST", url, bytes.NewReader(b))
  28. if err != nil {
  29. log.Error("NewRequest.Do(%d)(%s) error(%v)", dm.RoomID, url, err)
  30. }
  31. req.Header.Set("Content-type", "application/json")
  32. err = d.httpCli.Do(c, req, &res)
  33. if err == nil {
  34. break
  35. }
  36. log.Error("http.Do(%d)(%s) error(%v)", dm.RoomID, url, err)
  37. time.Sleep(50 * time.Millisecond)
  38. }
  39. if err != nil {
  40. log.Error("http.Do(%s) error(%v)", url, err)
  41. return
  42. }
  43. if res.Code != 0 {
  44. log.Error("http.Do(%s) res code(%d)", url, res.Code)
  45. }
  46. return
  47. }