Closed jwrookie closed 2 years ago
Because the fields in Time are not exported, which causes the above problem, I can use the following way to solve it
It's not a good code, it just solves the problem
package main
import (
"fmt"
"github.com/mitchellh/mapstructure"
"reflect"
"time"
)
type A struct {
T time.Time
Other string
}
type B struct {
T time.Time
Other string
}
func main() {
a := A{T: time.Now(), Other: "xxx"}
fmt.Printf("%#v\n", a)
var b B
MyDecode(a, &b)
fmt.Printf("%#v\n", b)
}
func ToTimeHookFunc() mapstructure.DecodeHookFunc {
var value interface{}
return func(from reflect.Value, to reflect.Value) (interface{}, error) {
if from.Type() == reflect.TypeOf(&time.Time{}) {
value = from.Interface()
}
if to.Type() == reflect.TypeOf(time.Time{}) {
return value, nil
}
return from.Interface(), nil
}
}
func MyDecode(input, output interface{}) {
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: nil,
DecodeHook: ToTimeHookFunc(),
Result: output,
})
err := decoder.Decode(input)
if err != nil {
panic(err)
}
}