pkg/runtime/serializer/codec_factory.go
对原始decoder、encoder的封装:
- 在decoder中会清除对象的GroupVersionKind
- 在encoder中,会在序列化时写入GroupVersionKind
// WithoutConversionCodecFactory is a CodecFactory that will explicitly ignore requests to perform conversion.// This wrapper is used while code migrates away from using conversion (such as external clients) and in the future// will be unnecessary when we change the signature of NegotiatedSerializer.type WithoutConversionCodecFactory struct {CodecFactory}// EncoderForVersion returns an encoder that does not do conversion, but does set the group version kind of the object// when serialized.func (f WithoutConversionCodecFactory) EncoderForVersion(serializer runtime.Encoder, version runtime.GroupVersioner) runtime.Encoder {return runtime.WithVersionEncoder{Version: version,Encoder: serializer,ObjectTyper: f.CodecFactory.scheme,}}// DecoderToVersion returns an decoder that does not do conversion.func (f WithoutConversionCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder {return runtime.WithoutVersionDecoder{Decoder: serializer,}}
WithoutVersionDecoder:
// WithoutVersionDecoder clears the group version kind of a deserialized object.type WithoutVersionDecoder struct {Decoder}// Decode does not do conversion. It removes the gvk during deserialization.func (d WithoutVersionDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {obj, gvk, err := d.Decoder.Decode(data, defaults, into)if obj != nil {kind := obj.GetObjectKind()// clearing the gvk is just a convention of a codeckind.SetGroupVersionKind(schema.GroupVersionKind{})}return obj, gvk, err}
WithVersionEncoder:
// WithVersionEncoder serializes an object and ensures the GVK is set.type WithVersionEncoder struct {Version GroupVersionerEncoderObjectTyper}// Encode does not do conversion. It sets the gvk during serialization.func (e WithVersionEncoder) Encode(obj Object, stream io.Writer) error {gvks, _, err := e.ObjectTyper.ObjectKinds(obj)if err != nil {if IsNotRegisteredError(err) {return e.Encoder.Encode(obj, stream)}return err}kind := obj.GetObjectKind()oldGVK := kind.GroupVersionKind()gvk := gvks[0]if e.Version != nil {preferredGVK, ok := e.Version.KindForGroupVersionKinds(gvks)if ok {gvk = preferredGVK}}kind.SetGroupVersionKind(gvk)err = e.Encoder.Encode(obj, stream)kind.SetGroupVersionKind(oldGVK)return err}
