forked from free5gc/openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
37 lines (30 loc) · 874 Bytes
/
convert.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
package openapi
import (
"fmt"
"reflect"
"time"
"github.com/mitchellh/mapstructure"
)
func openAPIDecodeHook(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) {
// convert OpenAPI DateTime to time.Time based on RFC3339
if to == reflect.TypeOf(time.Time{}) && from == reflect.TypeOf("") {
return time.Parse(time.RFC3339, v.(string))
}
return v, nil
}
// Convert - convert map[string]interface{} to openapi models
func Convert(from interface{}, to interface{}) error {
config := mapstructure.DecoderConfig{
DecodeHook: openAPIDecodeHook,
Result: to,
}
decoder, err := mapstructure.NewDecoder(&config)
if err != nil {
return fmt.Errorf("openapi: converter setup failed: %v", err)
}
err = decoder.Decode(from)
if err != nil {
return fmt.Errorf("openapi: convert to %v failed: %v", reflect.TypeOf(to), err)
}
return nil
}