...

Source file src/github.com/donovanhide/eventsource/encoder.go

Documentation: github.com/donovanhide/eventsource

     1  package eventsource
     2  
     3  import (
     4  	"compress/gzip"
     5  	"fmt"
     6  	"io"
     7  	"strings"
     8  )
     9  
    10  var (
    11  	encFields = []struct {
    12  		prefix string
    13  		value  func(Event) string
    14  	}{
    15  		{"id: ", Event.Id},
    16  		{"event: ", Event.Event},
    17  		{"data: ", Event.Data},
    18  	}
    19  )
    20  
    21  // An Encoder is capable of writing Events to a stream. Optionally
    22  // Events can be gzip compressed in this process.
    23  type Encoder struct {
    24  	w          io.Writer
    25  	compressed bool
    26  }
    27  
    28  // NewEncoder returns an Encoder for a given io.Writer.
    29  // When compressed is set to true, a gzip writer will be
    30  // created.
    31  func NewEncoder(w io.Writer, compressed bool) *Encoder {
    32  	if compressed {
    33  		return &Encoder{w: gzip.NewWriter(w), compressed: true}
    34  	}
    35  	return &Encoder{w: w}
    36  }
    37  
    38  // Encode writes an event in the format specified by the
    39  // server-sent events protocol.
    40  func (enc *Encoder) Encode(ev Event) error {
    41  	for _, field := range encFields {
    42  		prefix, value := field.prefix, field.value(ev)
    43  		if len(value) == 0 {
    44  			continue
    45  		}
    46  		value = strings.Replace(value, "\n", "\n"+prefix, -1)
    47  		if _, err := io.WriteString(enc.w, prefix+value+"\n"); err != nil {
    48  			return fmt.Errorf("eventsource encode: %v", err)
    49  		}
    50  	}
    51  	if _, err := io.WriteString(enc.w, "\n"); err != nil {
    52  		return fmt.Errorf("eventsource encode: %v", err)
    53  	}
    54  	if enc.compressed {
    55  		return enc.w.(*gzip.Writer).Flush()
    56  	}
    57  	return nil
    58  }
    59  

View as plain text