meta.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package json
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "k8s.io/kubernetes/pkg/api/unversioned"
  18. )
  19. // MetaFactory is used to store and retrieve the version and kind
  20. // information for JSON objects in a serializer.
  21. type MetaFactory interface {
  22. // Interpret should return the version and kind of the wire-format of
  23. // the object.
  24. Interpret(data []byte) (*unversioned.GroupVersionKind, error)
  25. }
  26. // DefaultMetaFactory is a default factory for versioning objects in JSON. The object
  27. // in memory and in the default JSON serialization will use the "kind" and "apiVersion"
  28. // fields.
  29. var DefaultMetaFactory = SimpleMetaFactory{}
  30. // SimpleMetaFactory provides default methods for retrieving the type and version of objects
  31. // that are identified with an "apiVersion" and "kind" fields in their JSON
  32. // serialization. It may be parameterized with the names of the fields in memory, or an
  33. // optional list of base structs to search for those fields in memory.
  34. type SimpleMetaFactory struct {
  35. }
  36. // Interpret will return the APIVersion and Kind of the JSON wire-format
  37. // encoding of an object, or an error.
  38. func (SimpleMetaFactory) Interpret(data []byte) (*unversioned.GroupVersionKind, error) {
  39. findKind := struct {
  40. APIVersion string `json:"apiVersion,omitempty"`
  41. Kind string `json:"kind,omitempty"`
  42. }{}
  43. if err := json.Unmarshal(data, &findKind); err != nil {
  44. return nil, fmt.Errorf("couldn't get version/kind; json parse error: %v", err)
  45. }
  46. gv, err := unversioned.ParseGroupVersion(findKind.APIVersion)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return &unversioned.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: findKind.Kind}, nil
  51. }