2021-05-22 16:12:26 -07:00
|
|
|
package protobuf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"github.com/golang/protobuf/proto"
|
|
|
|
"github.com/netsampler/goflow2/format"
|
2021-06-11 08:42:32 -07:00
|
|
|
"github.com/netsampler/goflow2/format/common"
|
2021-05-22 16:12:26 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
type ProtobufDriver struct {
|
|
|
|
fixedLen bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *ProtobufDriver) Prepare() error {
|
2021-06-11 08:42:32 -07:00
|
|
|
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 {
|
2021-06-11 08:42:32 -07:00
|
|
|
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")
|
|
|
|
}
|
2021-06-11 08:42:32 -07:00
|
|
|
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)
|
|
|
|
}
|