Path: blob/dev/pkg/fuzz/dataformat/dataformat.go
2070 views
package dataformat12import (3"errors"4"fmt"5)67// dataformats is a list of dataformats8var dataformats map[string]DataFormat910const (11// DefaultKey is the key i.e used when given12// data is not of k-v type13DefaultKey = "value"14)1516func init() {17dataformats = make(map[string]DataFormat)1819// register the default data formats20RegisterDataFormat(NewJSON())21RegisterDataFormat(NewXML())22RegisterDataFormat(NewRaw())23RegisterDataFormat(NewForm())24RegisterDataFormat(NewMultiPartForm())25}2627const (28// JSONDataFormat is the name of the JSON data format29JSONDataFormat = "json"30// XMLDataFormat is the name of the XML data format31XMLDataFormat = "xml"32// RawDataFormat is the name of the Raw data format33RawDataFormat = "raw"34// FormDataFormat is the name of the Form data format35FormDataFormat = "form"36// MultiPartFormDataFormat is the name of the MultiPartForm data format37MultiPartFormDataFormat = "multipart/form-data"38)3940// Get returns the dataformat by name41func Get(name string) DataFormat {42return dataformats[name]43}4445// RegisterEncoder registers an encoder46func RegisterDataFormat(dataformat DataFormat) {47dataformats[dataformat.Name()] = dataformat48}4950// DataFormat is an interface for encoding and decoding51type DataFormat interface {52// IsType returns true if the data is of the type53IsType(data string) bool54// Name returns the name of the encoder55Name() string56// Encode encodes the data into a format57Encode(data KV) (string, error)58// Decode decodes the data from a format59Decode(input string) (KV, error)60}6162// Decoded is a decoded data format63type Decoded struct {64// DataFormat is the data format65DataFormat string66// Data is the decoded data67Data KV68}6970// Decode decodes the data from a format71func Decode(data string) (*Decoded, error) {72for _, dataformat := range dataformats {73if dataformat.IsType(data) {74decoded, err := dataformat.Decode(data)75if err != nil {76return nil, err77}78value := &Decoded{79DataFormat: dataformat.Name(),80Data: decoded,81}82return value, nil83}84}85return nil, nil86}8788// Encode encodes the data into a format89func Encode(data KV, dataformat string) (string, error) {90if dataformat == "" {91return "", errors.New("dataformat is required")92}93if encoder, ok := dataformats[dataformat]; ok {94return encoder.Encode(data)95}96return "", fmt.Errorf("dataformat %s is not supported", dataformat)97}9899100