validate.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 ValidateBytes(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. return ValidateRawCfg(rawCfg)
  37. }
  38. func ValidateRawCfg(rawCfg interface{}) (*gojsonschema.Result, error) {
  39. rawCfg = ConvertKeysToStrings(rawCfg).(map[string]interface{})
  40. loader := gojsonschema.NewGoLoader(rawCfg)
  41. schemaLoader := gojsonschema.NewStringLoader(schema)
  42. return gojsonschema.Validate(schemaLoader, loader)
  43. }