Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/fuzz/dataformat/dataformat.go
2070 views
1
package dataformat
2
3
import (
4
"errors"
5
"fmt"
6
)
7
8
// dataformats is a list of dataformats
9
var dataformats map[string]DataFormat
10
11
const (
12
// DefaultKey is the key i.e used when given
13
// data is not of k-v type
14
DefaultKey = "value"
15
)
16
17
func init() {
18
dataformats = make(map[string]DataFormat)
19
20
// register the default data formats
21
RegisterDataFormat(NewJSON())
22
RegisterDataFormat(NewXML())
23
RegisterDataFormat(NewRaw())
24
RegisterDataFormat(NewForm())
25
RegisterDataFormat(NewMultiPartForm())
26
}
27
28
const (
29
// JSONDataFormat is the name of the JSON data format
30
JSONDataFormat = "json"
31
// XMLDataFormat is the name of the XML data format
32
XMLDataFormat = "xml"
33
// RawDataFormat is the name of the Raw data format
34
RawDataFormat = "raw"
35
// FormDataFormat is the name of the Form data format
36
FormDataFormat = "form"
37
// MultiPartFormDataFormat is the name of the MultiPartForm data format
38
MultiPartFormDataFormat = "multipart/form-data"
39
)
40
41
// Get returns the dataformat by name
42
func Get(name string) DataFormat {
43
return dataformats[name]
44
}
45
46
// RegisterEncoder registers an encoder
47
func RegisterDataFormat(dataformat DataFormat) {
48
dataformats[dataformat.Name()] = dataformat
49
}
50
51
// DataFormat is an interface for encoding and decoding
52
type DataFormat interface {
53
// IsType returns true if the data is of the type
54
IsType(data string) bool
55
// Name returns the name of the encoder
56
Name() string
57
// Encode encodes the data into a format
58
Encode(data KV) (string, error)
59
// Decode decodes the data from a format
60
Decode(input string) (KV, error)
61
}
62
63
// Decoded is a decoded data format
64
type Decoded struct {
65
// DataFormat is the data format
66
DataFormat string
67
// Data is the decoded data
68
Data KV
69
}
70
71
// Decode decodes the data from a format
72
func Decode(data string) (*Decoded, error) {
73
for _, dataformat := range dataformats {
74
if dataformat.IsType(data) {
75
decoded, err := dataformat.Decode(data)
76
if err != nil {
77
return nil, err
78
}
79
value := &Decoded{
80
DataFormat: dataformat.Name(),
81
Data: decoded,
82
}
83
return value, nil
84
}
85
}
86
return nil, nil
87
}
88
89
// Encode encodes the data into a format
90
func Encode(data KV, dataformat string) (string, error) {
91
if dataformat == "" {
92
return "", errors.New("dataformat is required")
93
}
94
if encoder, ok := dataformats[dataformat]; ok {
95
return encoder.Encode(data)
96
}
97
return "", fmt.Errorf("dataformat %s is not supported", dataformat)
98
}
99
100