request.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. var validate = validator.New(validator.WithRequiredStructEnabled())
  18. func BindingJson[O any](c *mqtt_client.MqttClient, item *router.Item, request any,
  19. responseIdentifier response.Identifier, sendFunc response.SendFunc[O]) bool {
  20. data := item.GetData()
  21. if data != nil && len(data) != 0 {
  22. if responseIdentifier != nil {
  23. err := json.Unmarshal(data, responseIdentifier)
  24. if err != nil {
  25. err := errors.New("Topic: " + item.Topic + " Response Identifier Unmarshal Error: " + err.Error())
  26. fslog.Error(err)
  27. return false
  28. }
  29. err = validate.Struct(responseIdentifier)
  30. if err != nil {
  31. err := errors.New("Topic: " + item.Topic + " Response Identifier Validate Error: " + err.Error())
  32. fslog.Error(err)
  33. return false
  34. }
  35. }
  36. if request != nil {
  37. err := json.Unmarshal(data, request)
  38. if err != nil {
  39. var zero O
  40. sendFunc(c, item, responseIdentifier, zero, err)
  41. return false
  42. }
  43. }
  44. }
  45. if request != nil {
  46. err := validate.Struct(request)
  47. if err != nil {
  48. var zero O
  49. sendFunc(c, item, responseIdentifier, zero, err)
  50. return false
  51. }
  52. }
  53. return true
  54. }