-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
88 lines (73 loc) · 1.95 KB
/
encoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package wukong
import (
"encoding/json"
"encoding/xml"
)
type (
Encoder interface {
MimeType() string // mime type
Encode(data []byte, val interface{}) error // encode data to val struct
Decode(val interface{}) ([]byte, error) // decode value to data
}
JSONEncoder struct{}
XMLEncoder struct{}
)
const (
MimeTypeJSON = "application/json"
MimeTypeJSON1 = "text/json"
MimeTypeJSON2 = "json"
MimeTypeXML = "application/xml"
MimeTypeXML1 = "text/xml"
MimeTypeXML2 = "/xml"
MimeTypeFormData = "application/x-www-form-urlencoded"
MimeTypeUrlencoded = "application/x-www-form-urlencoded"
MimeTypeHTML = "text/html"
MimeTypeText = "text/plain"
MimeTypeMultipart = "multipart/form-data"
)
var (
jsonEncoder = &JSONEncoder{}
xmlEncoder = &XMLEncoder{}
)
func Decode(contentType string, val interface{}) ([]byte, error) {
var coder Encoder
switch contentType {
case MimeTypeJSON, MimeTypeJSON1, MimeTypeJSON2:
coder = jsonEncoder
case MimeTypeXML, MimeTypeXML1, MimeTypeXML2:
coder = xmlEncoder
default:
coder = jsonEncoder
}
return coder.Decode(val)
}
func Encode(contentType string, data []byte, val interface{}) error {
var coder Encoder
switch contentType {
case MimeTypeJSON, MimeTypeJSON1, MimeTypeJSON2:
coder = jsonEncoder
case MimeTypeXML, MimeTypeXML1, MimeTypeXML2:
coder = xmlEncoder
default:
coder = jsonEncoder
}
return coder.Encode(data, val)
}
func (c *JSONEncoder) MimeType() string {
return MimeTypeJSON
}
func (c *JSONEncoder) Decode(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
func (c *JSONEncoder) Encode(data []byte, val interface{}) error {
return json.Unmarshal(data, val)
}
func (c *XMLEncoder) MimeType() string {
return MimeTypeXML
}
func (c *XMLEncoder) Decode(v interface{}) ([]byte, error) {
return xml.Marshal(v)
}
func (c *XMLEncoder) Encode(data []byte, val interface{}) error {
return xml.Unmarshal(data, val)
}