validate.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package config
  2. import (
  3. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  4. "github.com/xeipuuv/gojsonschema"
  5. )
  6. // ConvertKeysToStrings is temporarily copied from libcompose
  7. // TODO: just import this in the future
  8. func ConvertKeysToStrings(item interface{}) interface{} {
  9. switch typedDatas := item.(type) {
  10. case map[string]interface{}:
  11. for key, value := range typedDatas {
  12. typedDatas[key] = ConvertKeysToStrings(value)
  13. }
  14. return typedDatas
  15. case map[interface{}]interface{}:
  16. newMap := make(map[string]interface{})
  17. for key, value := range typedDatas {
  18. stringKey := key.(string)
  19. newMap[stringKey] = ConvertKeysToStrings(value)
  20. }
  21. return newMap
  22. case []interface{}:
  23. for i, value := range typedDatas {
  24. typedDatas[i] = ConvertKeysToStrings(value)
  25. }
  26. return typedDatas
  27. default:
  28. return item
  29. }
  30. }
  31. func Validate(bytes []byte) (*gojsonschema.Result, error) {
  32. var rawCfg map[string]interface{}
  33. if err := yaml.Unmarshal([]byte(bytes), &rawCfg); err != nil {
  34. return nil, err
  35. }
  36. rawCfg = ConvertKeysToStrings(rawCfg).(map[string]interface{})
  37. loader := gojsonschema.NewGoLoader(rawCfg)
  38. schemaLoader := gojsonschema.NewStringLoader(schema)
  39. return gojsonschema.Validate(schemaLoader, loader)
  40. }