request.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package request
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "git.sxidc.com/go-tools/api_binding/mqtt_binding/mqtt_client"
  6. "git.sxidc.com/go-tools/api_binding/mqtt_binding/mqtt_client/router"
  7. "git.sxidc.com/go-tools/api_binding/mqtt_binding/response"
  8. "git.sxidc.com/service-supports/fslog"
  9. "github.com/go-playground/validator/v10"
  10. )
  11. type CallerIdentifierRequest struct {
  12. CallerIdentifier string `json:"callerIdentifier" validate:"required"`
  13. }
  14. func (req *CallerIdentifierRequest) Identifier() string {
  15. return req.CallerIdentifier
  16. }
  17. func (req *CallerIdentifierRequest) Copy() response.Identifier {
  18. return &CallerIdentifierRequest{}
  19. }
  20. var validate = validator.New(validator.WithRequiredStructEnabled())
  21. func BindingJson[O any](c *mqtt_client.MqttClient, item *router.Item, request any,
  22. responseIdentifier response.Identifier, sendFunc response.SendFunc[O]) bool {
  23. data := item.GetData()
  24. if data != nil && len(data) != 0 {
  25. if responseIdentifier != nil {
  26. err := json.Unmarshal(data, responseIdentifier)
  27. if err != nil {
  28. err := errors.New("Topic: " + item.Topic + " Response Identifier Unmarshal Error: " + err.Error())
  29. fslog.Error(err)
  30. return false
  31. }
  32. err = validate.Struct(responseIdentifier)
  33. if err != nil {
  34. err := errors.New("Topic: " + item.Topic + " Response Identifier Validate Error: " + err.Error())
  35. fslog.Error(err)
  36. return false
  37. }
  38. }
  39. if request != nil {
  40. err := json.Unmarshal(data, request)
  41. if err != nil {
  42. fslog.Error(err)
  43. var zero O
  44. sendFunc(c, item, responseIdentifier, zero, err)
  45. return false
  46. }
  47. }
  48. }
  49. if request != nil {
  50. err := validate.Struct(request)
  51. if err != nil {
  52. fslog.Error(err)
  53. var zero O
  54. sendFunc(c, item, responseIdentifier, zero, err)
  55. return false
  56. }
  57. }
  58. return true
  59. }