github.com/whiteboxio/flow@v0.0.3-0.20190918184116-508d75d68a2c/pkg/corev1alpha1/x/encoder_base64.go (about)

     1  package x
     2  
     3  import (
     4  	"encoding/base64"
     5  	"sync"
     6  
     7  	core "github.com/awesome-flow/flow/pkg/corev1alpha1"
     8  )
     9  
    10  type EncoderBase64 struct {
    11  	name     string
    12  	ctx      *core.Context
    13  	queue    chan *core.Message
    14  	wg       sync.WaitGroup
    15  	encoding *base64.Encoding
    16  }
    17  
    18  var _ core.Actor = (*EncoderBase64)(nil)
    19  
    20  func NewEncoderBase64(name string, ctx *core.Context, params core.Params) (core.Actor, error) {
    21  	return &EncoderBase64{
    22  		name:     name,
    23  		ctx:      ctx,
    24  		queue:    make(chan *core.Message, 1),
    25  		encoding: base64.StdEncoding,
    26  	}, nil
    27  }
    28  
    29  func (e *EncoderBase64) Name() string {
    30  	return e.name
    31  }
    32  
    33  func (e *EncoderBase64) Start() error {
    34  	return nil
    35  }
    36  
    37  func (e *EncoderBase64) Stop() error {
    38  	close(e.queue)
    39  	e.wg.Wait()
    40  	return nil
    41  }
    42  
    43  func (e *EncoderBase64) Connect(nthreads int, peer core.Receiver) error {
    44  	for i := 0; i < nthreads; i++ {
    45  		e.wg.Add(1)
    46  		go func() {
    47  			for msg := range e.queue {
    48  				if err := peer.Receive(msg); err != nil {
    49  					e.ctx.Logger().Error("base64 encoder %q failed to send message to receiver: %s", e.name, err)
    50  				}
    51  			}
    52  			e.wg.Done()
    53  		}()
    54  	}
    55  	return nil
    56  }
    57  
    58  func (e *EncoderBase64) Receive(msg *core.Message) error {
    59  	encbody := e.encodeBase64(msg.Body())
    60  	msg.SetBody(encbody)
    61  	e.queue <- msg
    62  	return nil
    63  }
    64  
    65  func (e *EncoderBase64) encodeBase64(data []byte) []byte {
    66  	newlen := e.encoding.EncodedLen(len(data))
    67  	out := make([]byte, newlen)
    68  	e.encoding.Encode(out, data)
    69  	return out
    70  }