extension.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 runtime
  14. import (
  15. "bytes"
  16. "encoding/json"
  17. "errors"
  18. )
  19. func (re *RawExtension) UnmarshalJSON(in []byte) error {
  20. if re == nil {
  21. return errors.New("runtime.RawExtension: UnmarshalJSON on nil pointer")
  22. }
  23. if !bytes.Equal(in, []byte("null")) {
  24. re.Raw = append(re.Raw[0:0], in...)
  25. }
  26. return nil
  27. }
  28. // Marshal may get called on pointers or values, so implement MarshalJSON on value.
  29. // http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go
  30. func (re RawExtension) MarshalJSON() ([]byte, error) {
  31. if re.Raw == nil {
  32. // TODO: this is to support legacy behavior of JSONPrinter and YAMLPrinter, which
  33. // expect to call json.Marshal on arbitrary versioned objects (even those not in
  34. // the scheme). pkg/kubectl/resource#AsVersionedObjects and its interaction with
  35. // kubectl get on objects not in the scheme needs to be updated to ensure that the
  36. // objects that are not part of the scheme are correctly put into the right form.
  37. if re.Object != nil {
  38. return json.Marshal(re.Object)
  39. }
  40. return []byte("null"), nil
  41. }
  42. // TODO: Check whether ContentType is actually JSON before returning it.
  43. return re.Raw, nil
  44. }