-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.go
67 lines (61 loc) · 1.38 KB
/
decode.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
package web
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"gopkg.in/yaml.v2"
)
type Marshaller func(v interface{}) ([]byte, error)
func MarshallerFor(contentType string) (m Marshaller, err error) {
switch contentType {
case MimeHtml, MimePlain:
m = marshalText
case MimeJson, MimeJavascript:
m = json.Marshal
case MimeXml, MimeXml2:
m = xml.Marshal
case MimeYaml, MimeYaml2:
m = yaml.Marshal
default:
err = fmt.Errorf("unable to encode unrecognized contentType=%s", contentType)
return
}
return
}
func marshalText(value interface{}) ([]byte, error) {
switch value.(type) {
case string:
s, _ := value.(string) // TODO: Cleanup/revisit
return []byte(s), nil
case []byte:
b, _ := value.([]byte) // TODO: Cleanup/revisit
return b, nil
}
return []byte{}, fmt.Errorf("unable to transform value=%T to []byte", value)
}
func DecodeJson(src io.Reader, value interface{}) error {
decoder := json.NewDecoder(src)
if err := decoder.Decode(value); err != nil {
return err
}
return nil
}
func DecodeXml(src io.Reader, value interface{}) error {
decoder := xml.NewDecoder(src)
if err := decoder.Decode(value); err != nil {
return err
}
return nil
}
func DecodeYaml(src io.Reader, value interface{}) error {
in, err := ioutil.ReadAll(src)
if err != nil {
return err
}
if err := yaml.Unmarshal(in, value); err != nil {
return err
}
return nil
}