-
Notifications
You must be signed in to change notification settings - Fork 1
/
marshal.go
44 lines (38 loc) · 1.19 KB
/
marshal.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
package gophig
import (
"errors"
"fmt"
"strings"
)
// UnsupportedExtensionError is an error that is returned when a file extension is not supported.
type UnsupportedExtensionError struct {
extension string
}
// Error ...
func (e UnsupportedExtensionError) Error() string {
return fmt.Sprintf("error: gophig does not support the file extension '%s' at the moment", e.extension)
}
// IsUnsupportedExtensionErr returns true if the error is an UnsupportedExtensionError.
func IsUnsupportedExtensionErr(err error) bool {
var unsupportedExtensionError UnsupportedExtensionError
ok := errors.As(err, &unsupportedExtensionError)
return ok
}
// Marshaler is an interface that can marshal and unmarshal data.
type Marshaler interface {
Marshal(v interface{}) ([]byte, error)
Unmarshal(data []byte, v interface{}) error
}
// MarshalerFromExtension is a Marshaler that uses a file extension to determine which Marshaler to use.
func MarshalerFromExtension(ext string) (Marshaler, error) {
ext = strings.ToLower(ext)
switch ext {
case "toml":
return TOMLMarshaler{}, nil
case "json":
return JSONMarshaler{}, nil
case "yaml":
return YAMLMarshaler{}, nil
}
return nil, UnsupportedExtensionError{ext}
}