-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarshal.go
More file actions
34 lines (28 loc) · 714 Bytes
/
marshal.go
File metadata and controls
34 lines (28 loc) · 714 Bytes
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
package mappy
import (
"errors"
"fmt"
"reflect"
)
// ErrMapMarshal is returned when it is not possible to marshal struct into a map.
var ErrMapMarshal = errors.New("failed to marshal struct into map")
// Marshal transforms a custom struct into string->string map.
func Marshal(data interface{}) (m map[string]string, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v: %w", r, ErrMapMarshal)
}
}()
m = make(map[string]string)
rv := reflect.ValueOf(data)
elT := reflect.TypeOf(data)
for i := 0; i < rv.NumField(); i++ {
field := rv.Field(i)
ftype := elT.Field(i)
tag := ftype.Tag.Get("map")
if tag != "" {
m[tag] = field.String()
}
}
return m, nil
}