Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2014 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package runtime |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "encoding/json" |
| 22 | "errors" |
| 23 | ) |
| 24 | |
| 25 | func (re *RawExtension) UnmarshalJSON(in []byte) error { |
| 26 | if re == nil { |
| 27 | return errors.New("runtime.RawExtension: UnmarshalJSON on nil pointer") |
| 28 | } |
| 29 | if !bytes.Equal(in, []byte("null")) { |
| 30 | re.Raw = append(re.Raw[0:0], in...) |
| 31 | } |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | // Marshal may get called on pointers or values, so implement MarshalJSON on value. |
| 36 | // http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go |
| 37 | func (re RawExtension) MarshalJSON() ([]byte, error) { |
| 38 | if re.Raw == nil { |
| 39 | // TODO: this is to support legacy behavior of JSONPrinter and YAMLPrinter, which |
| 40 | // expect to call json.Marshal on arbitrary versioned objects (even those not in |
| 41 | // the scheme). pkg/kubectl/resource#AsVersionedObjects and its interaction with |
| 42 | // kubectl get on objects not in the scheme needs to be updated to ensure that the |
| 43 | // objects that are not part of the scheme are correctly put into the right form. |
| 44 | if re.Object != nil { |
| 45 | return json.Marshal(re.Object) |
| 46 | } |
| 47 | return []byte("null"), nil |
| 48 | } |
| 49 | // TODO: Check whether ContentType is actually JSON before returning it. |
| 50 | return re.Raw, nil |
| 51 | } |