...

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

Documentation: github.com/launchdarkly/eventsource

     1  package eventsource
     2  
     3  import (
     4  	"compress/gzip"
     5  	"fmt"
     6  	"io"
     7  	"strings"
     8  )
     9  
    10  var (
    11  	encFields = []struct { //nolint:gochecknoglobals // non-exported global that we treat as a constant
    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 or comment in the format specified by the
    39  // server-sent events protocol.
    40  func (enc *Encoder) Encode(ec eventOrComment) error {
    41  	switch item := ec.(type) {
    42  	case Event:
    43  		for _, field := range encFields {
    44  			prefix, value := field.prefix, field.value(item)
    45  			if len(value) == 0 {
    46  				continue
    47  			}
    48  			value = strings.Replace(value, "\n", "\n"+prefix, -1)
    49  			if _, err := io.WriteString(enc.w, prefix+value+"\n"); err != nil {
    50  				return fmt.Errorf("eventsource encode: %v", err)
    51  			}
    52  		}
    53  		if _, err := io.WriteString(enc.w, "\n"); err != nil {
    54  			return fmt.Errorf("eventsource encode: %v", err)
    55  		}
    56  	case comment:
    57  		line := ":" + item.value + "\n"
    58  		if _, err := io.WriteString(enc.w, line); err != nil {
    59  			return fmt.Errorf("eventsource encode: %v", err)
    60  		}
    61  	default:
    62  		return fmt.Errorf("unexpected parameter to Encode: %v", ec)
    63  	}
    64  	if enc.compressed {
    65  		return enc.w.(*gzip.Writer).Flush()
    66  	}
    67  	return nil
    68  }
    69  

View as plain text