1
0
mirror of https://github.com/netsampler/goflow2.git synced 2024-05-06 15:54:52 +00:00

47 lines
991 B
Go
Raw Normal View History

2021-05-22 16:12:26 -07:00
package protobuf
import (
"context"
"flag"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/netsampler/goflow2/format"
"github.com/netsampler/goflow2/format/common"
2021-05-22 16:12:26 -07:00
)
type ProtobufDriver struct {
fixedLen bool
}
func (d *ProtobufDriver) Prepare() error {
common.HashFlag()
2021-05-22 16:12:26 -07:00
flag.BoolVar(&d.fixedLen, "format.protobuf.fixedlen", false, "Prefix the protobuf with message length")
return nil
}
func (d *ProtobufDriver) Init(context.Context) error {
return common.ManualHashInit()
2021-05-22 16:12:26 -07:00
}
func (d *ProtobufDriver) Format(data interface{}) ([]byte, []byte, error) {
msg, ok := data.(proto.Message)
if !ok {
return nil, nil, fmt.Errorf("message is not protobuf")
}
key := common.HashProtoLocal(msg)
2021-05-22 16:12:26 -07:00
if !d.fixedLen {
b, err := proto.Marshal(msg)
return []byte(key), b, err
} else {
buf := proto.NewBuffer([]byte{})
err := buf.EncodeMessage(msg)
return []byte(key), buf.Bytes(), err
}
}
func init() {
d := &ProtobufDriver{}
format.RegisterFormatDriver("pb", d)
}