-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshaller.go
43 lines (38 loc) · 902 Bytes
/
marshaller.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
package golden
import (
"encoding/json"
"encoding/xml"
"errors"
"strings"
)
var (
ErrUnknownExtension = errors.New("unknown extension, please provide a custom Marshaller")
ErrInvalidType = errors.New("arg has an invalid type")
)
// Marshaller encodes v into a byte slice.
type Marshaller func(v interface{}) ([]byte, error)
// ByteMarshal assumes v will either be a string or a byte slice
// and marshals it accordingly.
func ByteMarshal(v interface{}) ([]byte, error) {
switch v := v.(type) {
case string:
return []byte(v), nil
case []byte:
return v, nil
default:
return nil, ErrInvalidType
}
}
func marshallerFor(extension string) (Marshaller, error) {
ext := strings.ToLower(extension)
switch ext {
case ".json":
return json.Marshal, nil
case ".xml":
return xml.Marshal, nil
case ".txt":
return ByteMarshal, nil
default:
return nil, ErrUnknownExtension
}
}