github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/watch/json/encoder.go (about) 1 /* 2 Copyright 2014 The Kubernetes Authors All rights reserved. 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 json 18 19 import ( 20 "encoding/json" 21 "io" 22 23 "k8s.io/kubernetes/pkg/runtime" 24 "k8s.io/kubernetes/pkg/watch" 25 ) 26 27 // Encoder implements the json.Encoder interface for io.Writers that 28 // should serialize WatchEvent objects into JSON. It will encode any object 29 // registered in the supplied codec and return an error otherwies. 30 type Encoder struct { 31 w io.Writer 32 encoder *json.Encoder 33 codec runtime.Codec 34 } 35 36 // NewEncoder creates an Encoder for the given writer and codec 37 func NewEncoder(w io.Writer, codec runtime.Codec) *Encoder { 38 return &Encoder{ 39 w: w, 40 encoder: json.NewEncoder(w), 41 codec: codec, 42 } 43 } 44 45 // Encode writes an event to the writer. Returns an error 46 // if the writer is closed or an object can't be encoded. 47 func (e *Encoder) Encode(event *watch.Event) error { 48 obj, err := Object(e.codec, event) 49 if err != nil { 50 return err 51 } 52 return e.encoder.Encode(obj) 53 }