github.com/hamba/avro@v1.8.0/encoder.go (about) 1 package avro 2 3 import ( 4 "io" 5 ) 6 7 // Encoder writes Avro values to an output stream. 8 type Encoder struct { 9 s Schema 10 w *Writer 11 } 12 13 // NewEncoder returns a new encoder that writes to w using schema s. 14 func NewEncoder(s string, w io.Writer) (*Encoder, error) { 15 sch, err := Parse(s) 16 if err != nil { 17 return nil, err 18 } 19 20 return NewEncoderForSchema(sch, w), nil 21 } 22 23 // NewEncoderForSchema returns a new encoder that writes to w using schema. 24 func NewEncoderForSchema(schema Schema, w io.Writer) *Encoder { 25 return DefaultConfig.NewEncoder(schema, w) 26 } 27 28 // Encode writes the Avro encoding of v to the stream. 29 func (e *Encoder) Encode(v interface{}) error { 30 e.w.WriteVal(e.s, v) 31 _ = e.w.Flush() 32 33 return e.w.Error 34 } 35 36 // Marshal returns the Avro encoding of v. 37 func Marshal(schema Schema, v interface{}) ([]byte, error) { 38 return DefaultConfig.Marshal(schema, v) 39 }