call.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package lic
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/xml"
  6. "fmt"
  7. "net/http"
  8. "time"
  9. model "go-common/app/job/main/tv/model/pgc"
  10. "go-common/library/log"
  11. "github.com/pkg/errors"
  12. )
  13. const (
  14. _normalCode = "0000"
  15. )
  16. func (d *Dao) callLic(c context.Context, url string, xmlBody string) (result *model.Document, err error) {
  17. var resp []byte
  18. result = &model.Document{}
  19. req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer([]byte(xmlBody)))
  20. if err != nil {
  21. log.Error("http.NewRequest err - %v", err)
  22. return
  23. }
  24. req.Header.Add("Content-Type", "text/xml; charset=utf-8")
  25. if resp, err = d.client.Raw(c, req); err != nil {
  26. log.Error("ClientGet error[%v]", err)
  27. return
  28. }
  29. if err = xml.Unmarshal(resp, result); err != nil {
  30. log.Error("XML Unmarshal %s, Error %v", string(resp), err)
  31. return
  32. }
  33. if result == nil || result.Response == nil {
  34. err = errors.Wrap(err, "Response Empty Error")
  35. return
  36. }
  37. if result.Response.ResponseCode != _normalCode {
  38. err = fmt.Errorf("Response Code Error %s", result.Response.ResponseCode)
  39. return
  40. }
  41. if result.Response.ErrorList != nil && result.Response.ErrorList.Error != nil {
  42. log.Warn("Response Error %v", result.Response.ErrorList.Error)
  43. }
  44. return
  45. }
  46. // CallRetry retries the xml call
  47. func (d *Dao) CallRetry(c context.Context, url string, xmlBody string) (result *model.Document, err error) {
  48. log.Info("callLic URL: %s, Body %s", url, xmlBody)
  49. for i := 0; i < 3; i++ {
  50. result, err = d.callLic(c, url, xmlBody)
  51. if err == nil {
  52. break
  53. }
  54. time.Sleep(10 * time.Second) // 5 seconds gap for each retrial
  55. }
  56. return
  57. }