map2struct.go 698 B

1234567891011121314151617181920212223242526272829303132333435
  1. package parser
  2. import (
  3. "fmt"
  4. "github.com/langgenius/dify-plugin-daemon/internal/types/validators"
  5. "github.com/mitchellh/mapstructure"
  6. )
  7. func MapToStruct[T any](m map[string]any) (*T, error) {
  8. var s T
  9. decoder := &mapstructure.DecoderConfig{
  10. Metadata: nil,
  11. Result: &s,
  12. TagName: "json",
  13. Squash: true,
  14. }
  15. d, err := mapstructure.NewDecoder(decoder)
  16. if err != nil {
  17. return nil, fmt.Errorf("error creating decoder: %s", err)
  18. }
  19. err = d.Decode(m)
  20. if err != nil {
  21. return nil, fmt.Errorf("error decoding map: %s", err)
  22. }
  23. if err := validators.GlobalEntitiesValidator.Struct(s); err != nil {
  24. return nil, fmt.Errorf("error validating struct: %s", err)
  25. }
  26. return &s, nil
  27. }