callback.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "encoding/hex"
  7. "encoding/json"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "go-common/app/admin/main/workflow/model"
  14. "go-common/library/ecode"
  15. "go-common/library/log"
  16. "github.com/pkg/errors"
  17. )
  18. // AllCallbacks return all callbacks in database
  19. func (d *Dao) AllCallbacks(c context.Context) (cbs map[int32]*model.Callback, err error) {
  20. cbs = make(map[int32]*model.Callback)
  21. cblist := make([]*model.Callback, 0)
  22. err = d.ReadORM.Table("workflow_callback").Find(&cblist).Error
  23. if err != nil {
  24. err = errors.WithStack(err)
  25. return
  26. }
  27. for _, cb := range cblist {
  28. cbs[cb.CbID] = cb
  29. }
  30. return
  31. }
  32. // SendCallback send callback to pre configured server
  33. func (d *Dao) SendCallback(c context.Context, cb *model.Callback, payload *model.Payload) (err error) {
  34. var (
  35. req *http.Request
  36. pdata []byte
  37. )
  38. if pdata, err = json.Marshal(payload); err != nil {
  39. return
  40. }
  41. // TODO:(zhoujiahui): with sign?
  42. uv := url.Values{}
  43. ts := strconv.FormatInt(time.Now().Unix(), 10)
  44. uv.Set("ts", ts)
  45. uv.Set("appkey", d.writeConf.Key)
  46. sign := sign(uv, d.writeConf.Key, d.writeConf.Secret, true)
  47. if req, err = http.NewRequest(http.MethodPost, cb.URL+"?ts="+ts+"&appkey="+d.writeConf.Key+"&sign="+sign, bytes.NewReader(pdata)); err != nil {
  48. return
  49. }
  50. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  51. res := &model.CommonResponse{}
  52. if err = d.httpWrite.Do(c, req, &res); err != nil {
  53. log.Error("d.httpWrite.Do(%+v) error(%v)", req, err)
  54. return
  55. }
  56. if res.Code != ecode.OK.Code() {
  57. log.Error("callback occur code error url(%s) body(%s) error code(%v)", req.URL, string(pdata), ecode.Int(res.Code))
  58. return
  59. }
  60. log.Info("send callback ok, req(%+v) body(%s) callback(%+v) ", req, string(pdata), cb)
  61. return
  62. }
  63. // sign is used to sign form params by given condition.
  64. func sign(params url.Values, appkey string, secret string, lower bool) (hexdigest string) {
  65. data := params.Encode()
  66. if strings.IndexByte(data, '+') > -1 {
  67. data = strings.Replace(data, "+", "%20", -1)
  68. }
  69. if lower {
  70. data = strings.ToLower(data)
  71. }
  72. digest := md5.Sum([]byte(data + secret))
  73. hexdigest = hex.EncodeToString(digest[:])
  74. return
  75. }