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